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.JSONObject;
14
import org.json.XML;
15
import org.springframework.beans.factory.annotation.Autowired;
16
import org.springframework.stereotype.Component;
17
import org.springframework.web.bind.annotation.CrossOrigin;
18

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

    
28

    
29
/**
30
 * Created by kiatrop on 15/4/2016.
31
 */
32
@Component
33
@CrossOrigin(origins = "*")
34
@Path("/claimsService")
35
public class ClaimsService {
36

    
37
    private static final Logger logger = Logger.getLogger(ClaimsService.class);
38

    
39
    @Autowired
40
    private FetchClaimHandler fetchClaimHandler = null;
41

    
42
    @Autowired
43
    private FetchProjectHandler fetchProjectHandler= null;
44

    
45
    @Autowired
46
    private FetchNotificationHandler fetchNotificationHandler = null;
47

    
48
    @Autowired
49
    private NotificationHandler notificationHandler = null;
50

    
51

    
52
    @Autowired
53
    private ClaimHandler claimHandler = null;
54

    
55
    @Autowired
56
    private DirectIndexHandler directIndexHandler = null;
57

    
58
    @Autowired
59
    public Authorization authorization = null;
60

    
61
    @Autowired
62
    private String defaultFrequencyInHours;
63

    
64
    @Autowired
65
    private EmailSender emailSender;
66

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

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

    
88
        if(authorization.isClaimCurator(token)) {
89

    
90
            int total = -1;
91

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

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

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

    
107
            }
108

    
109
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
110
        }
111

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

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

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

    
138
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
139
//        if(authorization.isProjectCurator(userInfo)) {
140
        String userMail = userInfo.getEmail();
141

    
142
        int total = -1;
143

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

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

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

    
175
                return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
176
            }
177

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

    
199

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

    
207
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
208
//        if(authorization.isProjectCurator(userInfo)) {
209
            String userMail = userInfo.getEmail();
210

    
211
            int total = -1;
212

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

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

    
240
                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
241
                }
242

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

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

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

    
271
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
272
            authorization.logStatus(token,cookie);
273
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
274
                    .type(MediaType.APPLICATION_JSON)
275
                    .build();
276
        }
277
//        logger.debug("Calling API for context with token " + token);
278
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
279
        if(authorization.isCommunityCurator(userInfo) || authorization.isClaimCurator(token) || this.emailSender.getCommunityUtils().isCommunityManager(contextId, userInfo.email)) {
280

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

    
289
            try {
290
                claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset, keyword, orderby, descending, types,false);
291
                total = fetchClaimHandler.countClaimsByContext(contextId, keyword, types);
292

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

    
299
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
300
        }
301

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

    
307

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

    
322

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

    
330
        if(authorization.isClaimCurator(token)) {
331

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

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

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

    
349
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
350
        }
351

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

    
357

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

    
371

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

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

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

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

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

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

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

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

    
425

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

    
432
        if(authorization.isRegistered(token)) {
433

    
434
            List<Claim> claims = null;
435

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

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

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

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

    
458
                return Response.status(200).entity(composeDataResponse(claim)).build();
459

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

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

    
484

    
485
        logger.debug("Header  \"Origin\" has value  " + origin);
486

    
487

    
488

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

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

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

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

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

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

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

    
520
    @DELETE
521
    @Path("/claims/bulk")
522
    @Produces(MediaType.APPLICATION_JSON)
523
    public Response deleteBulkClaims(@QueryParam("claimId") List<String> claimIds,
524
                                     @HeaderParam("X-XSRF-TOKEN") String token,
525
                                     @HeaderParam("Origin") String origin,
526
                                     @CookieParam("AccessToken") String  cookie){
527

    
528

    
529

    
530
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
531
             return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
532
                     .type(MediaType.APPLICATION_JSON)
533
                     .build();
534
         }
535

    
536

    
537
        ArrayList<String> deletedIds= new ArrayList<String>();
538
        ArrayList<String> notFoundIds= new ArrayList<String>();
539

    
540
        if (claimIds == null || claimIds.size() == 0) {
541
            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
542
                    .type(MediaType.APPLICATION_JSON).build();
543
        }
544

    
545
        logger.debug("Trying to delete claims with ids: " + claimIds.toString() + ".");
546
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
547
        for (String claimId : claimIds) {
548
            try {
549

    
550
                if (authorization.isRegistered(userInfo)) {
551
                    if (authorization.isClaimCurator(userInfo) || authorization.isCommunityCurator(userInfo) || userInfo.getEmail().equals(fetchClaimHandler.fetchClaimById(claimId,false).getUserMail())) {
552
                        if (claimHandler.deleteClaim(claimId)) {
553
                            deletedIds.add(claimId);
554
                        } else {
555
                            notFoundIds.add(claimId);
556
                        }
557
                    } else {
558
                        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to delete."))
559
                                .type(MediaType.APPLICATION_JSON)
560
                                .build();
561
                    }
562
                } else {
563
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
564
                            .type(MediaType.APPLICATION_JSON)
565
                            .build();
566
                }
567
            } catch (SQLStoreException|Exception e) {
568
                logger.error("Fail to delete claim with id " + claimId + ".", e);
569
                notFoundIds.add(claimId);
570
            }
571
        }
572
        logger.debug("Successfully deleted " + deletedIds.size() + " from " + claimIds.size()  +". Deleted claims with ids: " + deletedIds.toString() + ".");
573
        if (claimIds.size() == notFoundIds.size()) {
574
            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
575
                    .type(MediaType.APPLICATION_JSON).build();
576
        } else if (claimIds.size() == notFoundIds.size()) {
577
            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
578
        } else {
579
            return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
580
        }
581
    }
582

    
583
    @POST
584
    @Path("/claims")
585
    @Produces(MediaType.APPLICATION_JSON)
586
    @Consumes(MediaType.APPLICATION_JSON)
587
    public Response addClaim(String input, @Context HttpServletRequest request,
588
                             @HeaderParam("X-XSRF-TOKEN") String token,
589
                             @HeaderParam("Origin") String origin,
590
                             @CookieParam("AccessToken") String  cookie) {
591

    
592

    
593
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
594
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
595
                    .type(MediaType.APPLICATION_JSON)
596
                    .build();
597
        }
598

    
599
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
600
        if(authorization.isRegistered(userInfo)) {
601
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
602

    
603
            String claimedBy = userInfo.getEmail();
604
            logger.info("claimedBy " + claimedBy);
605

    
606
            EmailValidator emailValidator = EmailValidator.getInstance();
607
            if (!emailValidator.isValid(claimedBy)) {
608
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
609
                        .type(MediaType.APPLICATION_JSON).build();
610
            }
611

    
612

    
613
            try {
614
                String claimId = this.getInfoAndBuildClaim(jsonObject,claimedBy);
615
                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
616

    
617
            } catch (ClaimValidationException ve) {
618
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
619
                        .type(MediaType.APPLICATION_JSON).build();
620

    
621
            } catch (SQLStoreException|Exception e) {
622
                logger.error("Fail to add new claim.", e);
623
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
624
                        .type(MediaType.APPLICATION_JSON).build();
625
            }
626
        }
627
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access."))
628
                .type(MediaType.APPLICATION_JSON)
629
                .build();
630
    }
631

    
632
    @POST
633
    @Path("/claims/bulk")
634
    @Produces(MediaType.APPLICATION_JSON)
635
    @Consumes(MediaType.APPLICATION_JSON)
636
    public Response addBulkClaims(String input, @Context HttpServletRequest request,
637
                                  @HeaderParam("X-XSRF-TOKEN") String token,
638
                                  @HeaderParam("Origin") String origin,
639
                                  @CookieParam("AccessToken") String  cookie) {
640

    
641

    
642
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
643
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
644
                    .type(MediaType.APPLICATION_JSON)
645
                    .build();
646
        }
647

    
648
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
649
        if(authorization.isRegistered(userInfo)) {
650
            ArrayList<String> insertedIds = new ArrayList<String>();
651
            JsonArray errorInClaims = new JsonArray();
652

    
653
            int code200 = 0;
654
            int code400 = 0;
655
            int code500 = 0;
656

    
657
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
658
            for (JsonElement je : jsonArray) {
659
                JsonObject jsonObject = je.getAsJsonObject();
660

    
661
                String claimedBy = userInfo.getEmail();
662
                logger.info("claimedBy " + claimedBy);
663
                logger.debug(jsonObject);
664

    
665

    
666
                EmailValidator emailValidator = EmailValidator.getInstance();
667
                if (!emailValidator.isValid(claimedBy)) {
668
                    jsonObject.addProperty("error", "user");
669
                    logger.error("no valid user");
670
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
671
                    //                        .type(MediaType.APPLICATION_JSON).build();
672
                    code400++;
673
                    errorInClaims.add(jsonObject);
674
                }
675

    
676

    
677
                try {
678
                    String claimId = this.getInfoAndBuildClaim(jsonObject,claimedBy);
679
                    insertedIds.add(claimId);
680
                    code200++;
681
                    //                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
682

    
683
                } catch (ClaimValidationException ve) {
684
//                    logger.error("Validation Failed fo claim "+jsonObject);
685
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
686
                    //                        .type(MediaType.APPLICATION_JSON).build();
687
                    jsonObject.addProperty("error", "validation");
688
                    errorInClaims.add(jsonObject);
689
                    code400++;
690

    
691
                } catch (SQLStoreException|Exception e) {
692
                                    logger.error("Fail to add new claim.", e);
693
                    //                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
694
                    //                        .type(MediaType.APPLICATION_JSON).build();
695
                    jsonObject.addProperty("error", "insertion");
696
                    errorInClaims.add(jsonObject);
697
                    code500++;
698
                }
699
            }
700
            if (jsonArray.size() == code500) {
701
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
702
                        .type(MediaType.APPLICATION_JSON).build();
703
            } else if (code200 > 0) {
704
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
705
            } else {
706
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
707
                        .type(MediaType.APPLICATION_JSON).build();
708
            }
709
        }
710
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
711
                .type(MediaType.APPLICATION_JSON)
712
                .build();
713

    
714
    }
715
    @POST
716
    @Path("/curate/bulk")
717
    @Produces(MediaType.APPLICATION_JSON)
718
    @Consumes(MediaType.APPLICATION_JSON)
719
    public Response curateBulkClaims(String input, @Context HttpServletRequest request,
720
                                     @HeaderParam("X-XSRF-TOKEN") String token,
721
                                     @HeaderParam("Origin") String origin,
722
                                     @CookieParam("AccessToken") String  cookie) {
723

    
724

    
725
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
726
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
727
                    .type(MediaType.APPLICATION_JSON)
728
                    .build();
729
        }
730
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
731
        if (authorization.isRegistered(userInfo)) {
732
            ArrayList<String> insertedIds = new ArrayList<String>();
733
            JsonArray errorInClaims = new JsonArray();
734
            int code200 = 0;
735
            int code400 = 0;
736
            int code500 = 0;
737
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
738
            String curatedBy =userInfo.getEmail();
739

    
740
            for (JsonElement je : jsonArray) {
741
                JsonObject jsonObject = je.getAsJsonObject();
742

    
743
                 String id = jsonObject.get("id").getAsString();
744
                logger.info("id " + id);
745

    
746
                Boolean approved = jsonObject.get("approved").getAsBoolean();
747
                logger.info("approved " + approved);
748
                EmailValidator emailValidator = EmailValidator.getInstance();
749
                if (!emailValidator.isValid(curatedBy)) {
750
                    jsonObject.addProperty("error", "user");
751
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
752
                    //                        .type(MediaType.APPLICATION_JSON).build();
753
                    code400++;
754
                    errorInClaims.add(jsonObject);
755
                }
756

    
757
                try {
758
                    claimHandler.updateClaimCurationInfo(curatedBy,id, approved);
759
                    insertedIds.add(id);
760
                    code200++;
761

    
762
                } catch (SQLStoreException|Exception e) {
763
                    jsonObject.addProperty("error", "insertion");
764
                    errorInClaims.add(jsonObject);
765
                    code500++;
766
                }
767
            }
768
            if (jsonArray.size() == code500) {
769
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to update claims.", insertedIds, errorInClaims))
770
                        .type(MediaType.APPLICATION_JSON).build();
771
            } else if (code200 > 0) {
772
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
773
            } else {
774
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
775
                        .type(MediaType.APPLICATION_JSON).build();
776
            }
777
        }
778
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
779
                .type(MediaType.APPLICATION_JSON)
780
                .build();
781

    
782
    }
783
    @POST
784
    @Path("/feed/bulk")
785
    @Produces(MediaType.APPLICATION_JSON)
786
    @Consumes(MediaType.APPLICATION_JSON)
787
    public Response feedBulkRecords(String input, @Context HttpServletRequest request,
788
                                    @HeaderParam("X-XSRF-TOKEN") String token,
789
                                    @HeaderParam("Origin") String origin,
790
                                    @CookieParam("AccessToken") String  cookie) {
791

    
792

    
793
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
794

    
795
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
796
                    .type(MediaType.APPLICATION_JSON)
797
                    .build();
798
        }
799

    
800
        if (authorization.isRegistered(token)) {
801
            ArrayList<String> insertedIds = new ArrayList<String>();
802
            JsonArray errorInClaims = new JsonArray();
803
            int code200 = 0;
804
            int code400 = 0;
805
            int code500 = 0;
806
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
807
            for (JsonElement je : jsonArray) {
808
                JsonObject jsonObject = je.getAsJsonObject();
809
                Boolean inserted = directIndexHandler.insertRecord(new Gson().toJson(jsonObject.get("record")));
810
                if (inserted) {
811
                    insertedIds.add(jsonObject.get("id").getAsString());
812
                    code200++;
813
                } else {
814
                    errorInClaims.add(jsonObject.get("id").getAsString());
815
                    code400++;
816
                }
817

    
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

    
836
    @GET
837
    @Path("/users/notification")
838
    @Produces(MediaType.APPLICATION_JSON)
839
    public Response getUserEmailNotificationPreferences(@QueryParam("communityId") String openaireId,
840
                                  @HeaderParam("X-XSRF-TOKEN") String token,
841
                                  @CookieParam("AccessToken") String  cookie,
842
                                  @Context HttpServletRequest request) {
843
        
844
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
845
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
846
                    .type(MediaType.APPLICATION_JSON)
847
                    .build();
848
        }
849

    
850
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
851
        if(authorization.isRegistered(userInfo)) {
852
            String userMail = userInfo.getEmail();
853
            logger.debug("User is registerd "  );
854

    
855
            EmailValidator emailValidator = EmailValidator.getInstance();
856

    
857
            if (userMail == null || userMail.isEmpty()) {
858
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
859
                        .type(MediaType.APPLICATION_JSON).build();
860
            }
861

    
862
            if (!emailValidator.isValid(userMail)) {
863
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
864
                        .type(MediaType.APPLICATION_JSON).build();
865
            }
866

    
867
            List<Notification> notifications = null;
868
            try {
869
                if(openaireId != null) {
870
                    CommunityUtils communityInfo = this.emailSender.getCommunityUtils().getCommunityInfo(openaireId);
871
                    if(communityInfo.getManagers().contains(userMail) || authorization.isCommunityCurator(userInfo)) {
872

    
873
                        Notification notification = null;
874
                        logger.debug("About to fetch notification");
875
                        notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
876

    
877
                        if (notifications == null) {
878
                            notifications = new ArrayList<Notification>();
879
                        }
880
                        if (notification == null) {
881
                            notification = new Notification(openaireId, communityInfo.getName(), userMail, Integer.parseInt(defaultFrequencyInHours), true);
882
                        } else {
883
                            notification.setOpenaireName(communityInfo.getName());
884
                        }
885
                        notifications.add(notification);
886
                    }
887
                } else {
888
                    Map<String, String> projectIdsAndNames = fetchProjectHandler.fetchProjectIdsAndNamesByProjectManagerMail(userMail);
889
                    if(projectIdsAndNames != null) {
890
                        for (Map.Entry<String, String> projectIdAndName : projectIdsAndNames.entrySet()) {
891
                            Notification notification = null;
892
                            logger.debug("About to fetch notification");
893
                            notification = fetchNotificationHandler.fetchNotification(projectIdAndName.getKey(), userMail);
894

    
895
                            if (notifications == null) {
896
                                notifications = new ArrayList<Notification>();
897
                            }
898
                            if(notification == null) {
899
                                notification = new Notification(projectIdAndName.getKey(), projectIdAndName.getValue(), userMail, Integer.parseInt(defaultFrequencyInHours), true);
900
                            } else {
901
                                notification.setOpenaireName(projectIdAndName.getValue());
902
                            }
903
                            notifications.add(notification);
904
                            logger.debug(notification);
905
                            logger.debug("notification openaireId:"+notification.getOpenaireId());
906
                            logger.debug(notifications.size());
907
                        }
908
                    }
909
                }
910

    
911
            } catch (SQLStoreException|Exception e) {
912
                logger.error("Could not fetch notification preferences for user with mail " + userMail, e);
913
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
914
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
915
            }
916

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

    
921
            return Response.status(200).entity(composeDataResponse(notifications)).build();
922

    
923
        }
924
        logger.debug("User is *NOT* registerd "  );
925
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
926
                .type(MediaType.APPLICATION_JSON)
927
                .build();
928
    }
929

    
930
    @POST
931
    @Path("/users/notification/save")
932
    @Produces(MediaType.APPLICATION_JSON)
933
    @Consumes(MediaType.APPLICATION_JSON)
934
    public Response saveOrUpdateUserEmailNotificationPreferences(String input, @Context HttpServletRequest request,
935
                                     @HeaderParam("X-XSRF-TOKEN") String token,
936
                                     @HeaderParam("Origin") String origin,
937
                                     @CookieParam("AccessToken") String  cookie) {
938

    
939

    
940
        if(!authorization.hasBasicAuthorization(token, origin, cookie)){
941
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
942
                    .type(MediaType.APPLICATION_JSON)
943
                    .build();
944
        }
945
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
946
        if (authorization.isRegistered(userInfo)) {
947
            ArrayList<String> insertedIds = new ArrayList<String>();
948
            JsonArray errorInClaims = new JsonArray();
949
            int code200 = 0;
950
            int code400 = 0;
951
            int code500 = 0;
952
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
953

    
954
            String userMail =userInfo.getEmail();
955

    
956
            String openaireId = jsonObject.get("openaireId").getAsString();
957
            logger.info("openaireId " + openaireId);
958

    
959
            boolean notify = jsonObject.get("notify").getAsBoolean();
960
            logger.info("notify "+notify);
961

    
962
            int frequency = jsonObject.get("frequency").getAsInt();
963
            logger.info("frequency " + frequency);
964

    
965
            EmailValidator emailValidator = EmailValidator.getInstance();
966
            if (!emailValidator.isValid(userMail)) {
967
                jsonObject.addProperty("error", "user");
968
                                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
969
                                        .type(MediaType.APPLICATION_JSON).build();
970
            }
971

    
972
            try {
973
                boolean continueProcedure = false;
974
                List<String> managers = null;
975
                try {
976
                    managers = fetchProjectHandler.fetchContactEmailsByProjectId(openaireId);
977
                } catch (Exception e) {
978
                    e.printStackTrace();
979
                } catch (SQLStoreException e) {
980
                    e.printStackTrace();
981
                }
982
                if(managers != null && managers.contains(userMail)) {
983
                    continueProcedure = true;
984
                } else {
985
                    CommunityUtils communityInfo = this.emailSender.getCommunityUtils().getCommunityInfo(openaireId);
986
                    if(communityInfo.getManagers().contains(userMail) || authorization.isCommunityCurator(userInfo) ) {
987
                        continueProcedure = true;
988
                    }
989
                }
990

    
991
                if(continueProcedure) {
992
                    Notification notification = null;
993
                    logger.debug("About to fetch notification");
994
                    notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
995

    
996
                    if (notification == null) {
997
                        logger.debug("About to insert notification");
998
                        notificationHandler.buildAndInsertNotification(openaireId, userMail, frequency, notify);
999
                    } else {
1000
                        logger.debug("About to update notification");
1001
                        notificationHandler.updateNotificationPreferences(openaireId, userMail, frequency, notify);
1002
                    }
1003
                } else {
1004
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1005
                            .type(MediaType.APPLICATION_JSON)
1006
                            .build();
1007
                }
1008
            } catch (SQLStoreException|Exception e) {
1009
                logger.error("Could not save or update notification preferences for user with mail " + userMail, e);
1010
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch notification preferences" +
1011
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
1012
            }
1013

    
1014
            return Response.status(200).entity(compose200Message("Save or Update for notification successful")).type(MediaType.APPLICATION_JSON).build();
1015
        }
1016
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
1017
                .type(MediaType.APPLICATION_JSON)
1018
                .build();
1019
    }
1020

    
1021
    private String xml2Json(List<String> input) {
1022
        StringBuilder builder = new StringBuilder();
1023
        for(String category: input) {
1024
            builder.append(category);
1025
        }
1026
        return builder.toString();
1027
    }
1028

    
1029
    private  String compose200Message(String message){
1030
        return " { \"status\" : \"success\", \"code\": \"200\", \"message\" : \"  " + message +" \" }";
1031
    }
1032

    
1033
    private String compose204Message(String message) {
1034
        return  "{ \"status\" : \"error\", \"code\" : \"204\", \"message\" : \"  " + message +" \" }";
1035
    }
1036

    
1037
    private String compose400Message(String message) {
1038
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
1039
    }
1040

    
1041
    private String compose400Message(String message, Exception exception) {
1042
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
1043
                "\"description\" : \""+  exception.getMessage() +"\" }";
1044
    }
1045

    
1046
    private String compose403Message(String message) {
1047
        return  "{ \"status\" : \"error\", \"code\" : \"403\", \"message\" : \"  " + message +"\", " +
1048
                "\"description\" : \"\" }";
1049
    }
1050

    
1051
    private String compose404BulkDeleteMessage(String message, List<String> deletedIds, List<String> notFoundIds) {
1052
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \","+  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
1053
    }
1054
    private String compose404Message(String message) {
1055
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
1056
    }
1057

    
1058
    private String compose400BulkInsertMessage(String message, List<String> insertedIds,JsonArray errorInClaims) {
1059
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \""+  ", \"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1060
    }
1061

    
1062
    private String compose500Message(String message, Throwable throwable) {
1063
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1064
                "\"description\" : \""+  throwable.getMessage() +"\" }";
1065
    }
1066

    
1067
    private String compose500BulkInsertMessage(String message,  List<String> insertedIds, JsonArray errorInClaims) {
1068
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1069
                "\"description\" : \""+   "\" , " +  "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1070
    }
1071

    
1072
    /*
1073
    TODO check if needed
1074
    private String compose500BulkDeleteMessage(String message,  List<String> deletedIds, List<String> notFoundIds, Exception exception) {
1075
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1076
                "\"description\" : \""+  exception.getMessage() +"\" ," +  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
1077
    }
1078

    
1079

    
1080

    
1081
    TODO check if needed
1082
    private  String compose204Message(){
1083
        return " { \"status\" : \"success\", \"code\": \"204\" }";
1084
    } */
1085

    
1086
    private  String compose204BulkDeleteMessage(List<String> deletedIds, List<String> notFoundIds){
1087
        return " { \"status\" : \"success\", \"code\": \"204\", "+ "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + "}";
1088
    }
1089

    
1090

    
1091
    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
1092
        String url = request.getRequestURL().toString();
1093
        //String query = request.getQueryString();
1094

    
1095
        return " { \"status\" : \"success\", \"code\": \"201\", \"link\": \"" + url  +"/"+ claimId +"\" }";
1096
    }
1097
    private  String compose201BulkInsertMessage(List<String> insertedIds, JsonArray errorInClaims){
1098
        //String url = request.getRequestURL().toString();
1099
        //String query = request.getQueryString();
1100

    
1101
        return " { \"status\" : \"success\", \"code\": \"201\","+ "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims)+ "}";
1102
    }
1103
    private String composeDataResponse(HttpServletRequest request, List<Claim> claims, int total, int offset, int limit) {
1104
        if(offset != -1 && limit != -1) {   // if offset and limit are -1, no paging in the response
1105
            return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", " + composePaging(request, total, offset, limit) + ", "
1106
                    + "\"data\" : " + new Gson().toJson(claims) + " }";
1107
        } else {
1108
            return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", "
1109
                    + "\"data\" : " + new Gson().toJson(claims) + " }";
1110
        }
1111
    }
1112

    
1113
    private String composeDataResponse(String xml) {
1114
        return " { \"status\" : \"success\", \"code\": \"200\", "
1115
                + "\"data\" : " + XML.toJSONObject(xml).toString() + " }";
1116
    }
1117

    
1118
    private String composeDataResponse(Claim claim) {
1119
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(claim) + " }";
1120
    }
1121

    
1122
    private String composeDataResponse(List<Notification> notifications) {
1123
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(notifications) + " }";
1124
    }
1125

    
1126
    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
1127
        logger.info("total " + total);
1128
        logger.info("currentOffset " + currentOffset);
1129
        logger.info("limit " + limit);
1130

    
1131
        String url = request.getRequestURL().toString();
1132
        //String query = request.getQueryString();
1133

    
1134
        String first = url+"?offset=0&limit=20";
1135

    
1136
        int previousPage;
1137
        int nextPage;
1138
        int lastPage;
1139

    
1140
        if (total <= limit) {
1141
            lastPage = 0;
1142
        } else {
1143
            if(total%limit == 0) {
1144
                lastPage = total/limit-1;
1145
            } else {
1146
                lastPage = total/limit ;
1147
            }
1148
        }
1149
        String last = url+"?offset=" + lastPage + "&limit=20";
1150

    
1151
        if (currentOffset-1 <= 0) {
1152
            previousPage = 0;
1153
        } else {
1154
            previousPage = currentOffset-1;
1155
        }
1156
        String previous = url+"?offset=" + previousPage + "&limit=20";
1157

    
1158
        if (currentOffset+1 >= lastPage) {
1159
            nextPage = lastPage;
1160

    
1161
        } else {
1162
            nextPage = currentOffset + 1;
1163
        }
1164
        String next = url+"?offset=" + nextPage + "&limit=20";
1165

    
1166
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + first +"\"}, {\"rel\":\"last\", \"href\":\"" + last + "\"}, {\"rel\":\"previous\", \"href\": \"" + previous + "\"}, {\"rel\":\"next\", \"href\":\"" +  next +"\"}"+ "]";
1167
    }
1168
    private String composeTotalResults(int total) {
1169
        return "\"total\": \""+total+"\"";
1170
    }
1171

    
1172
     public static void main(String[] args) {
1173

    
1174
/*
1175
         EmailValidator emailValidator = EmailValidator.getInstance();
1176
         System.out.println(emailValidator.isValid("jate@gdddd"));
1177

    
1178
         InternetAddress emailAddr = null;
1179
         try {
1180
             emailAddr = new InternetAddress("jate@gdddd");
1181
             emailAddr.validate();
1182
         } catch (AddressException e) {
1183
             System.out.println("false");
1184
         }
1185
         System.out.println("true");
1186

    
1187
         ArrayList<String> insertedIds= new ArrayList<String>();
1188
         insertedIds.add("1");
1189
         insertedIds.add("2");
1190
         insertedIds.add("3");
1191
         System.out.println(helloWorldService.compose403Message("hello"));
1192

    
1193
*/
1194
//         BasicConfigurator.configure();
1195
//         ApplicationContext context = new ClassPathXmlApplicationContext("eu/dnetlib/openaire/rest/springContext-claims-authorization.xml");
1196
//
1197
//         Authorization authorization =  context.getBean(Authorization.class);
1198
//         UserHandler userHandler = context.getBean(UserHandler.class);
1199
//         System.out.println(authorization.getAdminRoles());
1200
//         authorization.isClaimCurator("eyJraWQiOiJvaWRjIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwOTMxNzMwMTMyODMzNjMyQG9wZW5taW50ZWQuZXUiLCJhenAiOiIyNGU4MzE3Ni0xMzEyLTRiYTMtYmMwYi1mZmVlYmVhMTYwM2UiLCJpc3MiOiJodHRwczpcL1wvYWFpLm9wZW5taW50ZWQuZXVcL29pZGNcLyIsImV4cCI6MTQ5ODQ4NTk3NiwiaWF0IjoxNDk4NDcxNTc2LCJqdGkiOiJkMWRlZjc1Yi00MTEyLTRiZDktYTIyNi0wZThhOWI2M2Y3MWQifQ.WVYOb_yO8OaxIIt2jRYEDQBhGGFRDTBw3DgtVV_smuN5yx1ScCj6aehLu3JKPSArme4m2SGF4TEGhpwNJkwhM2WapGtxmtuCmCzYIo_QlC1Yki9hr2OT2rXMcQsJCiKaBSf6pLue6Sn78GMB5yaUTvOQHRgidXGiZXH5lsuZUx15Q6Equ_wzond_rgP9mRheRkTyIFuvvg4PuzmudBc11Ty863vIIQtoWF7_p98zTbHxiNF9lLPwzPZKxDoQ8JeayQEC-jsWVLgxmp-h0jG_Ko5jFVVJeeosqMMucOrs2FT_NKHVYVqB6VVh0C6nOufeiLrNDeMUlDT4dAvKD2zE9w");
1201

    
1202
    }
1203

    
1204
//    @GET
1205
//    @Path("email-notifications")
1206
//    public void forceSendEmailNotifications() {
1207
//        emailSender.run();
1208
//    }
1209

    
1210
    @GET
1211
    @Path("test-email")
1212
    public void testEmail() {
1213
        ArrayList<String> list = new ArrayList<String>();
1214
        list.add("konstantinagalouni@gmail.com");
1215
        list.add("argirok@di.uoa.gr");
1216
        emailSender.send("openaire_id_test", "openaire_name_test", "community", list);
1217
    }
1218

    
1219
    private String getvalueOf(JsonObject jsonObject, String field){
1220
        String value = (jsonObject.get(field) != null && !jsonObject.get(field).isJsonNull())?jsonObject.get(field).getAsString():null;
1221
        logger.info(field + ": " + value);
1222
        return value;
1223

    
1224

    
1225
    }
1226
    private String getvalueOfDefault(JsonObject jsonObject, String field, String defaultValue){
1227
        String value = this.getvalueOf(jsonObject, field);
1228
        logger.debug("Field:"+field+"->"+value+"<-");
1229
        return (value!=null && !value.equals("")?value:defaultValue);
1230
    }
1231

    
1232
    private String getInfoAndBuildClaim(JsonObject jsonObject, String claimedBy ) throws SQLStoreException, Exception {
1233
        String claimedInDashboard = getvalueOfDefault(jsonObject, "claimedInDashboard", null);
1234

    
1235
        String sourceId = getvalueOf(jsonObject, "sourceId");
1236
        String sourceType = getvalueOf(jsonObject, "sourceType");
1237
        String sourceCollectedFrom = getvalueOf(jsonObject, "sourceCollectedFrom");
1238
        String sourceAccessRights = getvalueOf(jsonObject, "sourceAccessRights");
1239
        String sourceEmbargoEndDate = getvalueOfDefault(jsonObject, "sourceEmbargoEndDate", null);
1240

    
1241
        String targetId = getvalueOf(jsonObject, "targetId");
1242
        String targetType = getvalueOf(jsonObject, "targetType");
1243
        String targetCollectedFrom = getvalueOf(jsonObject, "targetCollectedFrom");
1244
        String targetAccessRights = getvalueOf(jsonObject, "targetAccessRights");
1245
        String targetEmbargoEndDate = getvalueOfDefault(jsonObject, "targetEmbargoEndDate", null);
1246

    
1247

    
1248
        logger.debug("Claimed in"+claimedInDashboard);
1249
        return claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate,claimedInDashboard);
1250
    }
1251
    
1252
  
1253
}
(2-2/3)