Project

General

Profile

1
package eu.dnetlib.openaire.rest;
2

    
3
import com.google.gson.*;
4
import eu.dnetlib.data.claims.entity.Claim;
5
import eu.dnetlib.data.claims.entity.Notification;
6
import eu.dnetlib.data.claims.handler.*;
7
import eu.dnetlib.data.claims.sql.SQLStoreException;
8
import eu.dnetlib.data.claims.utils.ClaimValidationException;
9
import eu.dnetlib.data.claims.utils.CommunityUtils;
10
import eu.dnetlib.data.emailSender.EmailSender;
11
import org.apache.commons.validator.EmailValidator;
12
import org.apache.log4j.Logger;
13
import org.json.XML;
14
import org.springframework.beans.factory.annotation.Autowired;
15
import org.springframework.stereotype.Component;
16

    
17
import javax.servlet.http.HttpServletRequest;
18
import javax.ws.rs.*;
19
import javax.ws.rs.core.Context;
20
import javax.ws.rs.core.MediaType;
21
import javax.ws.rs.core.Response;
22
import java.util.ArrayList;
23
import java.util.List;
24
import java.util.Map;
25

    
26

    
27
/**
28
 * Created by kiatrop on 15/4/2016.
29
 */
30
@Component
31
@Path("/claimsService")
32
public class ClaimsService {
33

    
34
    private static final Logger logger = Logger.getLogger(ClaimsService.class);
35

    
36
    @Autowired
37
    private FetchClaimHandler fetchClaimHandler = null;
38

    
39
    @Autowired
40
    private FetchProjectHandler fetchProjectHandler= null;
41

    
42
    @Autowired
43
    private FetchNotificationHandler fetchNotificationHandler = null;
44

    
45
    @Autowired
46
    private NotificationHandler notificationHandler = null;
47

    
48

    
49
    @Autowired
50
    private ClaimHandler claimHandler = null;
51

    
52
    @Autowired
53
    private DirectIndexHandler directIndexHandler = null;
54

    
55
    @Autowired
56
    public Authorization authorization = null;
57

    
58
    @Autowired
59
    private String defaultFrequencyInHours;
60

    
61
    @Autowired
62
    private EmailSender emailSender;
63

    
64
    @GET
65
    @Path("projects/{projectId}/claims")
66
    @Produces(MediaType.APPLICATION_JSON)
67
    public Response getProjectClaims(@PathParam("projectId") String projectId,
68
                           @DefaultValue("0") @QueryParam("offset") int offset,
69
                           @DefaultValue("20") @QueryParam("limit") int limit,
70
                           @DefaultValue("") @QueryParam("keyword") String keyword,
71
                           @DefaultValue("") @QueryParam("sortby") String orderby,
72
                           @DefaultValue("true") @QueryParam("descending") boolean descending,
73
                           @DefaultValue("") @QueryParam("types") List<String> types,
74
                                     @HeaderParam("X-XSRF-TOKEN") String token,
75
                                     @CookieParam("AccessToken") String  cookie,
76
                           @Context HttpServletRequest request) {
77

    
78
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
79
            authorization.logStatus(token,cookie);
80
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
81
                    .type(MediaType.APPLICATION_JSON)
82
                    .build();
83
        }
84

    
85
        if(authorization.isClaimCurator(token)) {
86

    
87
            int total = -1;
88

    
89
            if (projectId == null || projectId.isEmpty()) {
90
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
91
                        .type(MediaType.APPLICATION_JSON).build();
92
            }
93

    
94
            List<Claim> claims = null;
95
            try {
96
                claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types,false);
97
                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
98

    
99
            } catch (SQLStoreException|Exception e) {  //TODO check this with exception
100
                logger.error("Could not fetch claims for project with id " + projectId, e);
101
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
102
                        " for projects with id " + projectId + ".", e)).type(MediaType.APPLICATION_JSON).build();
103

    
104
            }
105

    
106
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
107
        }
108

    
109
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
110
                .type(MediaType.APPLICATION_JSON)
111
                .build();
112
    }
113

    
114
    @GET
115
    @Path("projects/{projectId}/all_claims")
116
    @Produces(MediaType.APPLICATION_JSON)
117
    public Response getAllProjectClaims(@PathParam("projectId") String projectId,
118
                                     @DefaultValue("-1") @QueryParam("offset") int offset,
119
                                     @DefaultValue("-1") @QueryParam("limit") int limit,
120
                                     @DefaultValue("") @QueryParam("keyword") String keyword,
121
                                     @DefaultValue("") @QueryParam("sortby") String orderby,
122
                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
123
                                     @DefaultValue("") @QueryParam("types") List<String> types,
124
                                     @HeaderParam("X-XSRF-TOKEN") String token,
125
                                     @CookieParam("AccessToken") String  cookie,
126
                                     @Context HttpServletRequest request) {
127

    
128
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
129
            authorization.logStatus(token,cookie);
130
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
131
                    .type(MediaType.APPLICATION_JSON)
132
                    .build();
133
        }
134

    
135
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
136
//        if(authorization.isProjectCurator(userInfo)) {
137
        String userMail = userInfo.getEmail();
138

    
139
        int total = -1;
140

    
141
        if (projectId == null || projectId.isEmpty()) {
142
            return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
143
                    .type(MediaType.APPLICATION_JSON).build();
144
        }
145

    
146
        List<Claim> claims = null;
147
        try {
148
            boolean forbidden = true;
149
            if(authorization.isProjectCurator(userInfo)) {
150
                forbidden = false;
151
            } else {
152
                List<String> contact_emails = fetchProjectHandler.fetchContactEmailsByProjectId(projectId);
153
                logger.debug(contact_emails);
154
                if(contact_emails != null && contact_emails.contains(userMail)) {
155
                    forbidden = false;
156
                }
157
            }
158

    
159
            if(forbidden){
160
                return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
161
                        .type(MediaType.APPLICATION_JSON)
162
                        .build();
163
            }else{
164
                if(offset == -1 && limit == -1) {
165
                    // when offset and limit are -1 fetch claims with null values, to ignore paging and limit clause
166
                    claims = fetchClaimHandler.fetchClaimsByProject(projectId, null, null, keyword, orderby, descending, types, true);
167
                } else {
168
                    claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types, true);
169
                }
170
                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
171

    
172
                return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
173
            }
174

    
175
        } catch (SQLStoreException|Exception e) {
176
            logger.error("Could not fetch claims for project with id " + projectId, e);
177
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
178
                    " for projects with id " + projectId + ".", e)).type(MediaType.APPLICATION_JSON).build();
179
        }
180
    }
181
/*
182
    @GET
183
    @Path("project/claims")
184
    @Produces(MediaType.APPLICATION_JSON)
185
    public Response getProjectClaimsByToken(@QueryParam("projectToken") String projectToken,
186
                                     @DefaultValue("-1") @QueryParam("offset") int offset,
187
                                     @DefaultValue("-1") @QueryParam("limit") int limit,
188
                                     @DefaultValue("") @QueryParam("keyword") String keyword,
189
                                     @DefaultValue("") @QueryParam("sortby") String orderby,
190
                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
191
                                     @DefaultValue("") @QueryParam("types") List<String> types,
192
                                     @HeaderParam("X-XSRF-TOKEN") String token,
193
                                     @CookieParam("AccessToken") String  cookie,
194
                                     @Context HttpServletRequest request) {
195

    
196

    
197
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
198
            authorization.logStatus(token,cookie);
199
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
200
                    .type(MediaType.APPLICATION_JSON)
201
                    .build();
202
        }
203

    
204
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
205
//        if(authorization.isProjectCurator(userInfo)) {
206
            String userMail = userInfo.getEmail();
207

    
208
            int total = -1;
209

    
210
            if (projectToken == null || projectToken.isEmpty()) {
211
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project token cannot be empty."))
212
                        .type(MediaType.APPLICATION_JSON).build();
213
            }
214

    
215
            List<Claim> claims = null;
216
            try {
217
                String projectId = null;
218
                if(authorization.isProjectCurator(userInfo)) {
219
                    projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken);
220
                } else {
221
                    projectId = fetchProjectHandler.fetchProjectIdByTokenAndEmail(projectToken, userMail);
222
                }
223
                //String projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken,userMail);
224
                if(projectId == null){
225
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
226
                            .type(MediaType.APPLICATION_JSON)
227
                            .build();
228
                }else{
229
                    if(offset == -1 && limit == -1) {
230
                        // when offset and limit are -1 fetch claims with null values, to ignore paging and limit clause
231
                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, null, null, keyword, orderby, descending, types, true);
232
                    } else {
233
                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types, true);
234
                    }
235
                    total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
236

    
237
                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
238
                }
239

    
240
            } catch (SQLStoreException|Exception e) {
241
                logger.error("Could not fetch claims for project token " + projectToken, e);
242
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
243
                        " for projects with token " + projectToken + ".", e)).type(MediaType.APPLICATION_JSON).build();
244
            }
245
//        }
246

    
247
//        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
248
//                .type(MediaType.APPLICATION_JSON)
249
//                .build();
250
    }
251
*/
252

    
253
    @GET
254
    @Path("/contexts/{contextId}/claims")
255
    @Produces(MediaType.APPLICATION_JSON)
256
    public Response getContextClaims(@PathParam("contextId") String contextId,
257
                           @DefaultValue("0") @QueryParam("offset") int offset,
258
                           @DefaultValue("20") @QueryParam("limit") int limit,
259
                           @DefaultValue("") @QueryParam("keyword") String keyword,
260
                           @DefaultValue("") @QueryParam("sortby") String orderby,
261
                           @DefaultValue("true") @QueryParam("descending") boolean descending,
262
                           @DefaultValue("") @QueryParam("types") List<String> types,
263
                                     @HeaderParam("X-XSRF-TOKEN") String token,
264
                                     @CookieParam("AccessToken") String  cookie,
265
                                     @Context HttpServletRequest request) {
266
//        @RequestParam(value="includeStates[]", defaultValue="1,2,3") String[] includeStates
267

    
268
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
269
            authorization.logStatus(token,cookie);
270
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
271
                    .type(MediaType.APPLICATION_JSON)
272
                    .build();
273
        }
274
//        logger.debug("Calling API for context with token " + token);
275

    
276
        if(authorization.isCommunityCurator(token) || authorization.isClaimCurator(token)) {
277

    
278
            int total = -1;
279
            if (contextId == null || contextId.isEmpty()) {
280
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
281
                        .type(MediaType.APPLICATION_JSON).build();
282
            }
283
            logger.debug("Types are " + types);
284
            List<Claim> claims = null;
285

    
286
            try {
287
                claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset, keyword, orderby, descending, types,false);
288
                total = fetchClaimHandler.countClaimsByContext(contextId, keyword, types);
289

    
290
            } catch (SQLStoreException|Exception e) {
291
                logger.error("Could not fetch claims for context with id " + contextId, e);
292
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
293
                        " for context with id " + contextId + ".", e)).type(MediaType.APPLICATION_JSON).build();
294
            }
295

    
296
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
297
        }
298

    
299
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
300
                .type(MediaType.APPLICATION_JSON)
301
                .build();
302
    }
303

    
304

    
305
    @GET
306
    @Path("/results/{resultId}/claims")
307
    @Produces(MediaType.APPLICATION_JSON)
308
    public Response getResultClaims(@PathParam("resultId") String resultId,
309
                                    @DefaultValue("0") @QueryParam("offset") int offset,
310
                                    @DefaultValue("20") @QueryParam("limit") int limit,
311
                                    @DefaultValue("") @QueryParam("keyword") String keyword,
312
                                    @DefaultValue("") @QueryParam("sortby") String orderby,
313
                                    @DefaultValue("true") @QueryParam("descending") boolean descending,
314
                                    @DefaultValue("") @QueryParam("types") List<String> types,
315
                                    @HeaderParam("X-XSRF-TOKEN") String token,
316
                                    @CookieParam("AccessToken") String  cookie,
317
                                    @Context HttpServletRequest request) {
318

    
319

    
320
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
321
            authorization.logStatus(token,cookie);
322
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
323
                    .type(MediaType.APPLICATION_JSON)
324
                    .build();
325
        }
326

    
327
        if(authorization.isClaimCurator(token)) {
328

    
329
            int total = -1;
330
            if (resultId == null || resultId.isEmpty()) {
331
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
332
                        .type(MediaType.APPLICATION_JSON).build();
333
            }
334

    
335
            List<Claim> claims = null;
336
            try {
337
                claims = fetchClaimHandler.fetchClaimsByResult(resultId, limit, offset, keyword, orderby, descending, types,false);
338
                total = fetchClaimHandler.countClaimsByResult(resultId, keyword, types);
339

    
340
            } catch (SQLStoreException|Exception e) {
341
                logger.error("Could not fetch claims for result with id " + resultId, e);
342
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
343
                        " for result with id " + resultId + ".", e)).type(MediaType.APPLICATION_JSON).build();
344
            }
345

    
346
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
347
        }
348

    
349
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
350
                .type(MediaType.APPLICATION_JSON)
351
                .build();
352
    }
353

    
354

    
355
    @GET
356
    @Path("/users/claims")
357
    @Produces(MediaType.APPLICATION_JSON)
358
    public Response getUserClaims(@DefaultValue("0") @QueryParam("offset") int offset,
359
                                  @DefaultValue("20") @QueryParam("limit") int limit,
360
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
361
                                  @DefaultValue("") @QueryParam("sortby") String orderby,
362
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
363
                                  @DefaultValue("") @QueryParam("types") List<String> types,
364
                                  @HeaderParam("X-XSRF-TOKEN") String token,
365
                                  @CookieParam("AccessToken") String  cookie,
366
                                  @Context HttpServletRequest request) {
367

    
368

    
369
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
370
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
371
                    .type(MediaType.APPLICATION_JSON)
372
                    .build();
373
        }
374

    
375
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
376
        if(authorization.isRegistered(userInfo)) {
377
            String userMail = userInfo.getEmail();
378
            logger.debug("User is registerd "  );
379
            int total = -1;
380
            EmailValidator emailValidator = EmailValidator.getInstance();
381

    
382
            if (userMail == null || userMail.isEmpty()) {
383
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
384
                        .type(MediaType.APPLICATION_JSON).build();
385
            }
386

    
387
            if (!emailValidator.isValid(userMail)) {
388
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
389
                        .type(MediaType.APPLICATION_JSON).build();
390
            }
391

    
392
            List<Claim> claims = null;
393
            try {
394
                logger.debug("About to fetch claims"  );
395
                claims = fetchClaimHandler.fetchClaimsByUser(userMail, limit, offset, keyword, orderby, descending, types,false);
396
                total = fetchClaimHandler.countClaimsByUser(userMail, keyword, types);
397

    
398
            } catch (SQLStoreException|Exception e) {
399
                logger.error("Could not fetch claims for user with mail " + userMail, e);
400
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
401
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
402
            }
403

    
404
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
405
        }
406
        logger.debug("User is *NOT* registerd "  );
407
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
408
                .type(MediaType.APPLICATION_JSON)
409
                .build();
410
    }
411

    
412
    @GET
413
    @Path("/claims/{claimId}")
414
    @Produces(MediaType.APPLICATION_JSON)
415
    public Response getClaimsById(@PathParam("claimId") String claimId,
416
                                  @DefaultValue("0") @QueryParam("offset") int offset,
417
                                  @DefaultValue("20") @QueryParam("limit") int limit,
418
                                  @HeaderParam("X-XSRF-TOKEN") String token,
419
                                  @CookieParam("AccessToken") String  cookie,
420
                                  @Context HttpServletRequest request) {
421

    
422

    
423
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
424
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
425
                    .type(MediaType.APPLICATION_JSON)
426
                    .build();
427
        }
428

    
429
        if(authorization.isRegistered(token)) {
430

    
431
            List<Claim> claims = null;
432

    
433
            int total = -1;
434
            if (claimId == null || claimId.isEmpty()) {
435
                try {
436
                    claims = fetchClaimHandler.fetchAllClaims(limit, offset,false);
437
                    total = fetchClaimHandler.countAllClaims("", new ArrayList<String>());
438

    
439
                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).type(MediaType.APPLICATION_JSON).build();
440

    
441
                } catch (SQLStoreException|Exception e) {
442
                    logger.error("Could not fetch claims.", e);
443
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
444
                            .type(MediaType.APPLICATION_JSON).build();
445
                }
446
            }
447

    
448
            try {
449
                Claim claim = fetchClaimHandler.fetchClaimById(claimId,false);
450
                if (claim == null) {
451
                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Cannot find claim with id " + claimId + "."))
452
                            .type(MediaType.APPLICATION_JSON).build();
453
                }
454

    
455
                return Response.status(200).entity(composeDataResponse(claim)).build();
456

    
457
            } catch (SQLStoreException|Exception e) {
458
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claim " +
459
                        "with id " + claimId + " id.", e)).type(MediaType.APPLICATION_JSON).build();
460
            }
461
        }
462
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
463
                .type(MediaType.APPLICATION_JSON)
464
                .build();
465
    }
466

    
467
    @GET
468
    @Path("/claims")
469
    @Produces(MediaType.APPLICATION_JSON)
470
    public Response getAllClaims(@DefaultValue("0") @QueryParam("offset") int offset,
471
                                  @DefaultValue("20") @QueryParam("limit") int limit,
472
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
473
                                  @DefaultValue("date") @QueryParam("sortby") String orderby,
474
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
475
                                  @DefaultValue("") @QueryParam("types") List<String> types,
476
                                 @HeaderParam("X-XSRF-TOKEN") String token,
477
                                 @HeaderParam("Origin") String origin,
478
                                 @CookieParam("AccessToken") String  cookie,
479
                                  @Context HttpServletRequest request) {
480

    
481

    
482
        logger.debug("Header  \"Origin\" has value  " + origin);
483

    
484

    
485

    
486
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
487
            logger.debug("User is not  authorized - Eroor 403");
488

    
489
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
490
                    .type(MediaType.APPLICATION_JSON)
491
                    .build();
492
        }
493

    
494
        if(authorization.isClaimCurator(token)) {
495
            logger.debug("User is authorized ! !");
496
            List<Claim> claims = null;
497

    
498
            int total = -1;
499
            try {
500
                claims = fetchClaimHandler.fetchAllClaims(limit, offset, keyword, orderby, descending, types,false);
501
                total = fetchClaimHandler.countAllClaims(keyword, types);
502

    
503
                return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
504

    
505
            } catch (SQLStoreException|Exception e) {
506
                logger.error("Could not fetch claims.", e);
507
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
508
                        .type(MediaType.APPLICATION_JSON).build();
509
            }
510
        }
511

    
512
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
513
               .type(MediaType.APPLICATION_JSON)
514
               .build();
515
    }
516

    
517
    //ARGIRO TODO: Na thn tsekarw
518
//    @POST
519
//    @Path("/claims/{claimId}")
520
//    @Produces(MediaType.APPLICATION_JSON)
521
//    public Response deleteClaim(@PathParam("claimId") String claimId,
522
//                                @QueryParam("token") String token) {
523
//
524
//        if(!JWTValidator.isValid(token)) {
525
//            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
526
//                    .type(MediaType.APPLICATION_JSON)
527
//                    .build();
528
//        }
529
//        try {
530
//
531
//            if (authorization.isRegistered(token) && (authorization.getUserHandler().getMail(token).equals(fetchClaimHandler.fetchClaimById(claimId).getUserMail()))) {
532
//                if (claimId == null || claimId.isEmpty()) {
533
//                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
534
//                            .type(MediaType.APPLICATION_JSON).build();
535
//                }
536
//
537
//                try {
538
//                    if (claimHandler.deleteClaim(claimId)) {
539
//                        return Response.status(204).entity(compose204Message()).type(MediaType.APPLICATION_JSON).build();
540
//                    }
541
//
542
//                } catch (Exception e) {
543
//                    logger.error("Fail to delete claim with id " + claimId + ".", e);
544
//                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId + ".", e))
545
//                            .type(MediaType.APPLICATION_JSON).build();
546
//                }
547
//
548
//                return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
549
//                        .type(MediaType.APPLICATION_JSON).build();
550
//            }
551
//
552
//            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
553
//                    .type(MediaType.APPLICATION_JSON)
554
//                    .build();
555
//
556
//        } catch (Exception e) {
557
//            logger.error("Could not fetch claims.", e);
558
//            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
559
//                    .type(MediaType.APPLICATION_JSON).build();
560
//        }
561
//    }
562
/*
563

    
564
    @DELETE
565
    @Path("/claims/{claimId}")
566
    public Response deleteClaim(@PathParam("claimId") String claimId) {
567

    
568
        if (claimId == null || claimId.isEmpty()) {
569
            return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
570
                    .header("Access-Control-Allow-Methods", "DELETE")
571
                    .type(MediaType.APPLICATION_JSON).build();
572
        }
573

    
574
        try {
575
            if(claimHandler.deleteClaim(claimId)) {
576
                return Response.status(204).entity(compose204Message()).header("Access-Control-Allow-Origin", "*")
577
                        .header("Access-Control-Allow-Methods", "DELETE").type(MediaType.APPLICATION_JSON).build();
578
            }
579

    
580
        } catch (Exception e) {return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
581
                    .type(MediaType.APPLICATION_JSON)
582
                    .build();
583
            logger.error("Fail to delete claim with id " + claimId + ".", e);
584
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId +".", e))
585
                    .header("Access-Control-Allow-Origin", "*")
586
                    .header("Access-Control-Allow-Methods", "DELETE")
587
                    .type(MediaType.APPLICATION_JSON).build();
588
        }
589

    
590
        return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
591
                .header("Access-Control-Allow-Methods", "DELETE")
592
                .type(MediaType.APPLICATION_JSON).build();
593
    }
594
 */
595
    @DELETE
596
    @Path("/claims/bulk")
597
    @Produces(MediaType.APPLICATION_JSON)
598
    public Response deleteBulkClaims(@QueryParam("claimId") List<String> claimIds,
599
                                     @HeaderParam("X-XSRF-TOKEN") String token,
600
                                     @HeaderParam("Origin") String origin,
601
                                     @CookieParam("AccessToken") String  cookie){
602

    
603

    
604

    
605
         if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
606
             return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
607
                     .type(MediaType.APPLICATION_JSON)
608
                     .build();
609
         }
610

    
611

    
612
        ArrayList<String> deletedIds= new ArrayList<String>();
613
        ArrayList<String> notFoundIds= new ArrayList<String>();
614

    
615
        if (claimIds == null || claimIds.size() == 0) {
616
            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
617
                    .type(MediaType.APPLICATION_JSON).build();
618
        }
619

    
620
        logger.debug("Trying to delete claims with ids: " + claimIds.toString() + ".");
621
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
622
        for (String claimId : claimIds) {
623
            try {
624

    
625
                if (authorization.isRegistered(userInfo)) {
626
                    if (authorization.isClaimCurator(userInfo) || authorization.isCommunityCurator(userInfo) || userInfo.getEmail().equals(fetchClaimHandler.fetchClaimById(claimId,false).getUserMail())) {
627
                        if (claimHandler.deleteClaim(claimId)) {
628
                            deletedIds.add(claimId);
629
                        } else {
630
                            notFoundIds.add(claimId);
631
                        }
632
                    } else {
633
                        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to delete."))
634
                                .type(MediaType.APPLICATION_JSON)
635
                                .build();
636
                    }
637
                } else {
638
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
639
                            .type(MediaType.APPLICATION_JSON)
640
                            .build();
641
                }
642
            } catch (SQLStoreException|Exception e) {
643
                logger.error("Fail to delete claim with id " + claimId + ".", e);
644
                notFoundIds.add(claimId);
645
            }
646
        }
647
        logger.debug("Successfully deleted " + deletedIds.size() + " from " + claimIds.size()  +". Deleted claims with ids: " + deletedIds.toString() + ".");
648
        if (claimIds.size() == notFoundIds.size()) {
649
            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
650
                    .type(MediaType.APPLICATION_JSON).build();
651
        } else if (claimIds.size() == notFoundIds.size()) {
652
            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
653
        } else {
654
            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
655
        }
656
    }
657

    
658
    @POST
659
    @Path("/claims")
660
    @Produces(MediaType.APPLICATION_JSON)
661
    @Consumes(MediaType.APPLICATION_JSON)
662
    public Response addClaim(String input, @Context HttpServletRequest request,
663
                             @HeaderParam("X-XSRF-TOKEN") String token,
664
                             @HeaderParam("Origin") String origin,
665
                             @CookieParam("AccessToken") String  cookie) {
666

    
667

    
668
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token) || !authorization.hasValidOrigin(origin)){
669
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
670
                    .type(MediaType.APPLICATION_JSON)
671
                    .build();
672
        }
673

    
674
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
675
        if(authorization.isRegistered(userInfo)) {
676
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
677

    
678
            String claimedBy = userInfo.getEmail();
679
            logger.info("claimedBy " + claimedBy);
680

    
681
            String sourceId = jsonObject.get("sourceId").getAsString();
682
            logger.info("sourceId " + sourceId);
683
            String sourceType = jsonObject.get("sourceType").getAsString();
684
            logger.info("sourceType " + sourceType);
685
            String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
686
            logger.info("sourceCollectedFrom " + sourceCollectedFrom);
687
            String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
688
            logger.info("sourceAccessRights " + sourceAccessRights);
689
            String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
690
            sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
691
            logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
692

    
693
            String targetId = jsonObject.get("targetId").getAsString();
694
            logger.info("targetId " + targetId);
695
            String targetType = jsonObject.get("targetType").getAsString();
696
            logger.info("targetType " + targetType);
697
            String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
698
            logger.info("targetCollectedFrom " + targetCollectedFrom);
699
            String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
700
            logger.info("targetAccessRights " + targetAccessRights);
701
            String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
702
            targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
703
            logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
704

    
705
            EmailValidator emailValidator = EmailValidator.getInstance();
706
            if (!emailValidator.isValid(claimedBy)) {
707
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
708
                        .type(MediaType.APPLICATION_JSON).build();
709
            }
710

    
711

    
712
            try {
713
                String claimId = claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate);
714
                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
715

    
716
            } catch (ClaimValidationException ve) {
717
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
718
                        .type(MediaType.APPLICATION_JSON).build();
719

    
720
            } catch (SQLStoreException|Exception e) {
721
                logger.error("Fail to add new claim.", e);
722
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
723
                        .type(MediaType.APPLICATION_JSON).build();
724
            }
725
        }
726
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access."))
727
                .type(MediaType.APPLICATION_JSON)
728
                .build();
729
    }
730

    
731
    @POST
732
    @Path("/claims/bulk")
733
    @Produces(MediaType.APPLICATION_JSON)
734
    @Consumes(MediaType.APPLICATION_JSON)
735
    public Response addBulkClaims(String input, @Context HttpServletRequest request,
736
                                  @HeaderParam("X-XSRF-TOKEN") String token,
737
                                  @HeaderParam("Origin") String origin,
738
                                  @CookieParam("AccessToken") String  cookie) {
739

    
740

    
741
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
742
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
743
                    .type(MediaType.APPLICATION_JSON)
744
                    .build();
745
        }
746

    
747
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
748
        if(authorization.isRegistered(userInfo)) {
749
            ArrayList<String> insertedIds = new ArrayList<String>();
750
            JsonArray errorInClaims = new JsonArray();
751

    
752
            int code200 = 0;
753
            int code400 = 0;
754
            int code500 = 0;
755

    
756
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
757
            for (JsonElement je : jsonArray) {
758
                JsonObject jsonObject = je.getAsJsonObject();
759

    
760
                logger.info("targetId " + jsonObject.toString());
761
                String claimedBy = userInfo.getEmail();
762
                logger.info("claimedBy " + claimedBy);
763

    
764
                String sourceId = jsonObject.get("sourceId").getAsString();
765
                logger.info("sourceId " + sourceId);
766
                String sourceType = jsonObject.get("sourceType").getAsString();
767
                logger.info("sourceType " + sourceType);
768
                String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
769
                logger.info("sourceCollectedFrom " + sourceCollectedFrom);
770
                String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
771
                logger.info("sourceAccessRights " + sourceAccessRights);
772
                String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
773
                sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
774
                logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
775

    
776
                String targetId = jsonObject.get("targetId").getAsString();
777
                logger.info("targetId " + targetId);
778
                String targetType = jsonObject.get("targetType").getAsString();
779
                logger.info("targetType " + targetType);
780
                String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
781
                logger.info("targetCollectedFrom " + targetCollectedFrom);
782
                String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
783
                logger.info("targetAccessRights " + targetAccessRights);
784
                String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
785
                targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
786
                logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
787

    
788
                EmailValidator emailValidator = EmailValidator.getInstance();
789
                if (!emailValidator.isValid(claimedBy)) {
790
                    jsonObject.addProperty("error", "user");
791
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
792
                    //                        .type(MediaType.APPLICATION_JSON).build();
793
                    code400++;
794
                    errorInClaims.add(jsonObject);
795
                }
796

    
797

    
798
                try {
799
                    String claimId = claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate);
800
                    insertedIds.add(claimId);
801
                    code200++;
802
                    //                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
803

    
804
                } catch (ClaimValidationException ve) {
805
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
806
                    //                        .type(MediaType.APPLICATION_JSON).build();
807
                    jsonObject.addProperty("error", "validation");
808
                    errorInClaims.add(jsonObject);
809
                    code400++;
810

    
811
                } catch (SQLStoreException|Exception e) {
812
                    //                logger.error("Fail to add new claim.", e);
813
                    //                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
814
                    //                        .type(MediaType.APPLICATION_JSON).build();
815
                    jsonObject.addProperty("error", "insertion");
816
                    errorInClaims.add(jsonObject);
817
                    code500++;
818
                }
819
            }
820
            if (jsonArray.size() == code500) {
821
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
822
                        .type(MediaType.APPLICATION_JSON).build();
823
            } else if (code200 > 0) {
824
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
825
            } else {
826
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
827
                        .type(MediaType.APPLICATION_JSON).build();
828
            }
829
        }
830
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
831
                .type(MediaType.APPLICATION_JSON)
832
                .build();
833

    
834
    }
835
    @POST
836
    @Path("/curate/bulk")
837
    @Produces(MediaType.APPLICATION_JSON)
838
    @Consumes(MediaType.APPLICATION_JSON)
839
    public Response curateBulkClaims(String input, @Context HttpServletRequest request,
840
                                     @HeaderParam("X-XSRF-TOKEN") String token,
841
                                     @HeaderParam("Origin") String origin,
842
                                     @CookieParam("AccessToken") String  cookie) {
843

    
844

    
845
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
846
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
847
                    .type(MediaType.APPLICATION_JSON)
848
                    .build();
849
        }
850
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
851
        if (authorization.isRegistered(userInfo)) {
852
            ArrayList<String> insertedIds = new ArrayList<String>();
853
            JsonArray errorInClaims = new JsonArray();
854
            int code200 = 0;
855
            int code400 = 0;
856
            int code500 = 0;
857
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
858
            String curatedBy =userInfo.getEmail();
859

    
860
            for (JsonElement je : jsonArray) {
861
                JsonObject jsonObject = je.getAsJsonObject();
862

    
863
                 String id = jsonObject.get("id").getAsString();
864
                logger.info("id " + id);
865

    
866
                Boolean approved = jsonObject.get("approved").getAsBoolean();
867
                logger.info("approved " + approved);
868
                EmailValidator emailValidator = EmailValidator.getInstance();
869
                if (!emailValidator.isValid(curatedBy)) {
870
                    jsonObject.addProperty("error", "user");
871
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
872
                    //                        .type(MediaType.APPLICATION_JSON).build();
873
                    code400++;
874
                    errorInClaims.add(jsonObject);
875
                }
876

    
877
                try {
878
                    claimHandler.updateClaimCurationInfo(curatedBy,id, approved);
879
                    insertedIds.add(id);
880
                    code200++;
881

    
882
                } catch (SQLStoreException|Exception e) {
883
                    jsonObject.addProperty("error", "insertion");
884
                    errorInClaims.add(jsonObject);
885
                    code500++;
886
                }
887
            }
888
            if (jsonArray.size() == code500) {
889
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to update claims.", insertedIds, errorInClaims))
890
                        .type(MediaType.APPLICATION_JSON).build();
891
            } else if (code200 > 0) {
892
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
893
            } else {
894
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
895
                        .type(MediaType.APPLICATION_JSON).build();
896
            }
897
        }
898
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
899
                .type(MediaType.APPLICATION_JSON)
900
                .build();
901

    
902
    }
903
    @POST
904
    @Path("/feed/bulk")
905
    @Produces(MediaType.APPLICATION_JSON)
906
    @Consumes(MediaType.APPLICATION_JSON)
907
    public Response feedBulkRecords(String input, @Context HttpServletRequest request,
908
                                    @HeaderParam("X-XSRF-TOKEN") String token,
909
                                    @HeaderParam("Origin") String origin,
910
                                    @CookieParam("AccessToken") String  cookie) {
911

    
912

    
913
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
914

    
915
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
916
                    .type(MediaType.APPLICATION_JSON)
917
                    .build();
918
        }
919

    
920
        if (authorization.isRegistered(token)) {
921
            ArrayList<String> insertedIds = new ArrayList<String>();
922
            JsonArray errorInClaims = new JsonArray();
923
            int code200 = 0;
924
            int code400 = 0;
925
            int code500 = 0;
926
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
927
            for (JsonElement je : jsonArray) {
928
                JsonObject jsonObject = je.getAsJsonObject();
929
                Boolean inserted = directIndexHandler.insertRecord(new Gson().toJson(jsonObject.get("record")));
930
                if (inserted) {
931
                    insertedIds.add(jsonObject.get("id").getAsString());
932
                    code200++;
933
                } else {
934
                    errorInClaims.add(jsonObject.get("id").getAsString());
935
                    code400++;
936
                }
937

    
938

    
939
            }
940
            if (jsonArray.size() == code500) {
941
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
942
                        .type(MediaType.APPLICATION_JSON).build();
943
            } else if (code200 > 0) {
944
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
945
            } else {
946
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
947
                        .type(MediaType.APPLICATION_JSON).build();
948
            }
949
        }
950
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
951
                .type(MediaType.APPLICATION_JSON)
952
                .build();
953

    
954
    }
955

    
956
    @GET
957
    @Path("/users/notification")
958
    @Produces(MediaType.APPLICATION_JSON)
959
    public Response getUserEmailNotificationPreferences(@QueryParam("communityId") String openaireId,
960
                                  @HeaderParam("X-XSRF-TOKEN") String token,
961
                                  @CookieParam("AccessToken") String  cookie,
962
                                  @Context HttpServletRequest request) {
963
        
964
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
965
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
966
                    .type(MediaType.APPLICATION_JSON)
967
                    .build();
968
        }
969

    
970
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
971
        if(authorization.isRegistered(userInfo)) {
972
            String userMail = userInfo.getEmail();
973
            logger.debug("User is registerd "  );
974

    
975
            EmailValidator emailValidator = EmailValidator.getInstance();
976

    
977
            if (userMail == null || userMail.isEmpty()) {
978
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
979
                        .type(MediaType.APPLICATION_JSON).build();
980
            }
981

    
982
            if (!emailValidator.isValid(userMail)) {
983
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
984
                        .type(MediaType.APPLICATION_JSON).build();
985
            }
986

    
987
            List<Notification> notifications = null;
988
            try {
989
                if(openaireId != null) {
990
                    CommunityUtils communityInfo = CommunityUtils.getCommunityInfo(openaireId);
991
                    if(communityInfo.getManagers().contains(userMail)) {
992

    
993
                        Notification notification = null;
994
                        logger.debug("About to fetch notification");
995
                        notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
996

    
997
                        if (notifications == null) {
998
                            notifications = new ArrayList<Notification>();
999
                        }
1000
                        if (notification == null) {
1001
                            notification = new Notification(openaireId, communityInfo.getName(), userMail, Integer.parseInt(defaultFrequencyInHours), true);
1002
                        } else {
1003
                            notification.setOpenaireName(communityInfo.getName());
1004
                        }
1005
                        notifications.add(notification);
1006
                    }
1007
                } else {
1008
                    Map<String, String> projectIdsAndNames = fetchProjectHandler.fetchProjectIdsAndNamesByProjectManagerMail(userMail);
1009
                    if(projectIdsAndNames != null) {
1010
                        for (Map.Entry<String, String> projectIdAndName : projectIdsAndNames.entrySet()) {
1011
                            Notification notification = null;
1012
                            logger.debug("About to fetch notification");
1013
                            notification = fetchNotificationHandler.fetchNotification(projectIdAndName.getKey(), userMail);
1014

    
1015
                            if (notifications == null) {
1016
                                notifications = new ArrayList<Notification>();
1017
                            }
1018
                            if(notification == null) {
1019
                                notification = new Notification(projectIdAndName.getKey(), projectIdAndName.getValue(), userMail, Integer.parseInt(defaultFrequencyInHours), true);
1020
                            } else {
1021
                                notification.setOpenaireName(projectIdAndName.getValue());
1022
                            }
1023
                            notifications.add(notification);
1024
                            logger.debug(notification);
1025
                            logger.debug("notification openaireId:"+notification.getOpenaireId());
1026
                            logger.debug(notifications.size());
1027
                        }
1028
                    }
1029
                }
1030

    
1031
            } catch (SQLStoreException|Exception e) {
1032
                logger.error("Could not fetch notification preferences for user with mail " + userMail, e);
1033
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
1034
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
1035
            }
1036

    
1037
            if (notifications == null || notifications.isEmpty()) {
1038
                return Response.status(204).entity(compose204Message("There are no notifications for user with mail " + userMail)).type(MediaType.APPLICATION_JSON).build();
1039
            }
1040

    
1041
            return Response.status(200).entity(composeDataResponse(notifications)).build();
1042

    
1043
        }
1044
        logger.debug("User is *NOT* registerd "  );
1045
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1046
                .type(MediaType.APPLICATION_JSON)
1047
                .build();
1048
    }
1049

    
1050
    @POST
1051
    @Path("/users/notification/save")
1052
    @Produces(MediaType.APPLICATION_JSON)
1053
    @Consumes(MediaType.APPLICATION_JSON)
1054
    public Response saveOrUpdateUserEmailNotificationPreferences(String input, @Context HttpServletRequest request,
1055
                                     @HeaderParam("X-XSRF-TOKEN") String token,
1056
                                     @HeaderParam("Origin") String origin,
1057
                                     @CookieParam("AccessToken") String  cookie) {
1058

    
1059

    
1060
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
1061
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
1062
                    .type(MediaType.APPLICATION_JSON)
1063
                    .build();
1064
        }
1065
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
1066
        if (authorization.isRegistered(userInfo)) {
1067
            ArrayList<String> insertedIds = new ArrayList<String>();
1068
            JsonArray errorInClaims = new JsonArray();
1069
            int code200 = 0;
1070
            int code400 = 0;
1071
            int code500 = 0;
1072
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
1073

    
1074
            String userMail =userInfo.getEmail();
1075

    
1076
            String openaireId = jsonObject.get("openaireId").getAsString();
1077
            logger.info("openaireId " + openaireId);
1078

    
1079
            boolean notify = jsonObject.get("notify").getAsBoolean();
1080
            logger.info("notify "+notify);
1081

    
1082
            int frequency = jsonObject.get("frequency").getAsInt();
1083
            logger.info("frequency " + frequency);
1084

    
1085
            EmailValidator emailValidator = EmailValidator.getInstance();
1086
            if (!emailValidator.isValid(userMail)) {
1087
                jsonObject.addProperty("error", "user");
1088
                                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
1089
                                        .type(MediaType.APPLICATION_JSON).build();
1090
            }
1091

    
1092
            try {
1093
                boolean continueProcedure = false;
1094
                List<String> managers = null;
1095
                try {
1096
                    managers = fetchProjectHandler.fetchContactEmailsByProjectId(openaireId);
1097
                } catch (Exception e) {
1098
                    e.printStackTrace();
1099
                } catch (SQLStoreException e) {
1100
                    e.printStackTrace();
1101
                }
1102
                if(managers != null && managers.contains(userMail)) {
1103
                    continueProcedure = true;
1104
                } else {
1105
                    CommunityUtils communityInfo = CommunityUtils.getCommunityInfo(openaireId);
1106
                    if(communityInfo.getManagers().contains(userMail)) {
1107
                        continueProcedure = true;
1108
                    }
1109
                }
1110

    
1111
                if(continueProcedure) {
1112
                    Notification notification = null;
1113
                    logger.debug("About to fetch notification");
1114
                    notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
1115

    
1116
                    if (notification == null) {
1117
                        logger.debug("About to insert notification");
1118
                        notificationHandler.buildAndInsertNotification(openaireId, userMail, frequency, notify);
1119
                    } else {
1120
                        logger.debug("About to update notification");
1121
                        notificationHandler.updateNotificationPreferences(openaireId, userMail, frequency, notify);
1122
                    }
1123
                } else {
1124
                    Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1125
                            .type(MediaType.APPLICATION_JSON)
1126
                            .build();
1127
                }
1128
            } catch (SQLStoreException|Exception e) {
1129
                logger.error("Could not save or update notification preferences for user with mail " + userMail, e);
1130
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
1131
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
1132
            }
1133

    
1134
            return Response.status(200).entity(compose204Message("Save or Update for notification successful")).type(MediaType.APPLICATION_JSON).build();
1135
        }
1136
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1137
                .type(MediaType.APPLICATION_JSON)
1138
                .build();
1139
    }
1140

    
1141
    private String xml2Json(List<String> input) {
1142
        StringBuilder builder = new StringBuilder();
1143
        for(String category: input) {
1144
            builder.append(category);
1145
        }
1146
        return builder.toString();
1147
    }
1148

    
1149
    private String compose204Message(String message) {
1150
        return  "{ \"status\" : \"error\", \"code\" : \"204\", \"message\" : \"  " + message +" \" }";
1151
    }
1152

    
1153
    private String compose400Message(String message) {
1154
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
1155
    }
1156

    
1157
    private String compose400Message(String message, Exception exception) {
1158
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
1159
                "\"description\" : \""+  exception.getMessage() +"\" }";
1160
    }
1161

    
1162
    private String compose403Message(String message) {
1163
        return  "{ \"status\" : \"error\", \"code\" : \"403\", \"message\" : \"  " + message +"\", " +
1164
                "\"description\" : \"\" }";
1165
    }
1166

    
1167
    private String compose404BulkDeleteMessage(String message, List<String> deletedIds, List<String> notFoundIds) {
1168
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \","+  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
1169
    }
1170
    private String compose404Message(String message) {
1171
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
1172
    }
1173

    
1174
    private String compose400BulkInsertMessage(String message, List<String> insertedIds,JsonArray errorInClaims) {
1175
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \""+  ", \"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1176
    }
1177

    
1178
    private String compose500Message(String message, Throwable throwable) {
1179
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1180
                "\"description\" : \""+  throwable.getMessage() +"\" }";
1181
    }
1182

    
1183
    private String compose500BulkInsertMessage(String message,  List<String> insertedIds, JsonArray errorInClaims) {
1184
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1185
                "\"description\" : \""+   "\" , " +  "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1186
    }
1187

    
1188
    /*
1189
    TODO check if needed
1190
    private String compose500BulkDeleteMessage(String message,  List<String> deletedIds, List<String> notFoundIds, Exception exception) {
1191
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1192
                "\"description\" : \""+  exception.getMessage() +"\" ," +  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
1193
    }
1194

    
1195
    TODO check if needed
1196
    private  String compose200Message(){
1197
        return " { \"status\" : \"success\", \"code\": \"200\" }";
1198
    }
1199

    
1200
    TODO check if needed
1201
    private  String compose204Message(){
1202
        return " { \"status\" : \"success\", \"code\": \"204\" }";
1203
    } */
1204

    
1205
    private  String compose204BulkDeleteMessage(List<String> deletedIds, List<String> notFoundIds){
1206
        return " { \"status\" : \"success\", \"code\": \"204\", "+ "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + "}";
1207
    }
1208

    
1209

    
1210
    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
1211
        String url = request.getRequestURL().toString();
1212
        //String query = request.getQueryString();
1213

    
1214
        return " { \"status\" : \"success\", \"code\": \"201\", \"link\": \"" + url  +"/"+ claimId +"\" }";
1215
    }
1216
    private  String compose201BulkInsertMessage(List<String> insertedIds, JsonArray errorInClaims){
1217
        //String url = request.getRequestURL().toString();
1218
        //String query = request.getQueryString();
1219

    
1220
        return " { \"status\" : \"success\", \"code\": \"201\","+ "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims)+ "}";
1221
    }
1222
    private String composeDataResponse(HttpServletRequest request, List<Claim> claims, int total, int offset, int limit) {
1223
        if(offset != -1 && limit != -1) {   // if offset and limit are -1, no paging in the response
1224
            return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", " + composePaging(request, total, offset, limit) + ", "
1225
                    + "\"data\" : " + new Gson().toJson(claims) + " }";
1226
        } else {
1227
            return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", "
1228
                    + "\"data\" : " + new Gson().toJson(claims) + " }";
1229
        }
1230
    }
1231

    
1232
    private String composeDataResponse(String xml) {
1233
        return " { \"status\" : \"success\", \"code\": \"200\", "
1234
                + "\"data\" : " + XML.toJSONObject(xml).toString() + " }";
1235
    }
1236

    
1237
    private String composeDataResponse(Claim claim) {
1238
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(claim) + " }";
1239
    }
1240

    
1241
    private String composeDataResponse(List<Notification> notifications) {
1242
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(notifications) + " }";
1243
    }
1244

    
1245
    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
1246
        logger.info("total " + total);
1247
        logger.info("currentOffset " + currentOffset);
1248
        logger.info("limit " + limit);
1249

    
1250
        String url = request.getRequestURL().toString();
1251
        //String query = request.getQueryString();
1252

    
1253
        String first = url+"?offset=0&limit=20";
1254

    
1255
        int previousPage;
1256
        int nextPage;
1257
        int lastPage;
1258

    
1259
        if (total <= limit) {
1260
            lastPage = 0;
1261
        } else {
1262
            if(total%limit == 0) {
1263
                lastPage = total/limit-1;
1264
            } else {
1265
                lastPage = total/limit ;
1266
            }
1267
        }
1268
        String last = url+"?offset=" + lastPage + "&limit=20";
1269

    
1270
        if (currentOffset-1 <= 0) {
1271
            previousPage = 0;
1272
        } else {
1273
            previousPage = currentOffset-1;
1274
        }
1275
        String previous = url+"?offset=" + previousPage + "&limit=20";
1276

    
1277
        if (currentOffset+1 >= lastPage) {
1278
            nextPage = lastPage;
1279

    
1280
        } else {
1281
            nextPage = currentOffset + 1;
1282
        }
1283
        String next = url+"?offset=" + nextPage + "&limit=20";
1284

    
1285
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + first +"\"}, {\"rel\":\"last\", \"href\":\"" + last + "\"}, {\"rel\":\"previous\", \"href\": \"" + previous + "\"}, {\"rel\":\"next\", \"href\":\"" +  next +"\"}"+ "]";
1286
    }
1287
    private String composeTotalResults(int total) {
1288
        return "\"total\": \""+total+"\"";
1289
    }
1290

    
1291
     public static void main(String[] args) {
1292

    
1293
/*
1294
         EmailValidator emailValidator = EmailValidator.getInstance();
1295
         System.out.println(emailValidator.isValid("jate@gdddd"));
1296

    
1297
         InternetAddress emailAddr = null;
1298
         try {
1299
             emailAddr = new InternetAddress("jate@gdddd");
1300
             emailAddr.validate();
1301
         } catch (AddressException e) {
1302
             System.out.println("false");
1303
         }
1304
         System.out.println("true");
1305

    
1306
         ArrayList<String> insertedIds= new ArrayList<String>();
1307
         insertedIds.add("1");
1308
         insertedIds.add("2");
1309
         insertedIds.add("3");
1310
         System.out.println(helloWorldService.compose403Message("hello"));
1311

    
1312
*/
1313
//         BasicConfigurator.configure();
1314
//         ApplicationContext context = new ClassPathXmlApplicationContext("eu/dnetlib/openaire/rest/springContext-claims-authorization.xml");
1315
//
1316
//         Authorization authorization =  context.getBean(Authorization.class);
1317
//         UserHandler userHandler = context.getBean(UserHandler.class);
1318
//         System.out.println(authorization.getAdminRoles());
1319
//         authorization.isClaimCurator("eyJraWQiOiJvaWRjIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwOTMxNzMwMTMyODMzNjMyQG9wZW5taW50ZWQuZXUiLCJhenAiOiIyNGU4MzE3Ni0xMzEyLTRiYTMtYmMwYi1mZmVlYmVhMTYwM2UiLCJpc3MiOiJodHRwczpcL1wvYWFpLm9wZW5taW50ZWQuZXVcL29pZGNcLyIsImV4cCI6MTQ5ODQ4NTk3NiwiaWF0IjoxNDk4NDcxNTc2LCJqdGkiOiJkMWRlZjc1Yi00MTEyLTRiZDktYTIyNi0wZThhOWI2M2Y3MWQifQ.WVYOb_yO8OaxIIt2jRYEDQBhGGFRDTBw3DgtVV_smuN5yx1ScCj6aehLu3JKPSArme4m2SGF4TEGhpwNJkwhM2WapGtxmtuCmCzYIo_QlC1Yki9hr2OT2rXMcQsJCiKaBSf6pLue6Sn78GMB5yaUTvOQHRgidXGiZXH5lsuZUx15Q6Equ_wzond_rgP9mRheRkTyIFuvvg4PuzmudBc11Ty863vIIQtoWF7_p98zTbHxiNF9lLPwzPZKxDoQ8JeayQEC-jsWVLgxmp-h0jG_Ko5jFVVJeeosqMMucOrs2FT_NKHVYVqB6VVh0C6nOufeiLrNDeMUlDT4dAvKD2zE9w");
1320

    
1321
    }
1322

    
1323
//    @GET
1324
//    @Path("email-notifications")
1325
//    public void forceSendEmailNotifications() {
1326
//        emailSender.run();
1327
//    }
1328

    
1329
    @GET
1330
    @Path("test-email")
1331
    public void testEmail() {
1332
        ArrayList<String> list = new ArrayList<String>();
1333
        list.add("konstantinagalouni@gmail.com");
1334
        list.add("argirok@di.uoa.gr");
1335
        emailSender.send("openaire_id_test", "openaire_name_test", "community", list);
1336
    }
1337
}
(2-2/3)