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 (notification != null) {
878
                            notifications = new ArrayList<Notification>();
879
                            notification.setOpenaireName(communityInfo.getName());
880
                            notifications.add(notification);
881
                        }
882
                    }
883
                } else {
884
                    Map<String, String> projectIdsAndNames = fetchProjectHandler.fetchProjectIdsAndNamesByProjectManagerMail(userMail);
885
                    if(projectIdsAndNames != null) {
886
                        for (Map.Entry<String, String> projectIdAndName : projectIdsAndNames.entrySet()) {
887
                            Notification notification = null;
888
                            logger.debug("About to fetch notification");
889
                            notification = fetchNotificationHandler.fetchNotification(projectIdAndName.getKey(), userMail);
890

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

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

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

    
917
            return Response.status(200).entity(composeDataResponse(notifications)).build();
918

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

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

    
935

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

    
950
            String userMail =userInfo.getEmail();
951

    
952
            String openaireId = jsonObject.get("openaireId").getAsString();
953
            logger.info("openaireId " + openaireId);
954

    
955
            boolean notify = jsonObject.get("notify").getAsBoolean();
956
            logger.info("notify "+notify);
957

    
958
            int frequency = jsonObject.get("frequency").getAsInt();
959
            logger.info("frequency " + frequency);
960

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

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

    
987
                if(continueProcedure) {
988
                    Notification notification = null;
989
                    logger.debug("About to fetch notification");
990
                    notification = fetchNotificationHandler.fetchNotification(openaireId, userMail);
991

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

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

    
1017
    private String xml2Json(List<String> input) {
1018
        StringBuilder builder = new StringBuilder();
1019
        for(String category: input) {
1020
            builder.append(category);
1021
        }
1022
        return builder.toString();
1023
    }
1024

    
1025
    private  String compose200Message(String message){
1026
        return " { \"status\" : \"success\", \"code\": \"200\", \"message\" : \"  " + message +" \" }";
1027
    }
1028

    
1029
    private String compose204Message(String message) {
1030
        return  "{ \"status\" : \"error\", \"code\" : \"204\", \"message\" : \"  " + message +" \" }";
1031
    }
1032

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

    
1037
    private String compose400Message(String message, Exception exception) {
1038
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
1039
                "\"description\" : \""+  exception.getMessage() +"\" }";
1040
    }
1041

    
1042
    private String compose403Message(String message) {
1043
        return  "{ \"status\" : \"error\", \"code\" : \"403\", \"message\" : \"  " + message +"\", " +
1044
                "\"description\" : \"\" }";
1045
    }
1046

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

    
1054
    private String compose400BulkInsertMessage(String message, List<String> insertedIds,JsonArray errorInClaims) {
1055
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \""+  ", \"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1056
    }
1057

    
1058
    private String compose500Message(String message, Throwable throwable) {
1059
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1060
                "\"description\" : \""+  throwable.getMessage() +"\" }";
1061
    }
1062

    
1063
    private String compose500BulkInsertMessage(String message,  List<String> insertedIds, JsonArray errorInClaims) {
1064
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1065
                "\"description\" : \""+   "\" , " +  "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1066
    }
1067

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

    
1075

    
1076

    
1077
    TODO check if needed
1078
    private  String compose204Message(){
1079
        return " { \"status\" : \"success\", \"code\": \"204\" }";
1080
    } */
1081

    
1082
    private  String compose204BulkDeleteMessage(List<String> deletedIds, List<String> notFoundIds){
1083
        return " { \"status\" : \"success\", \"code\": \"204\", "+ "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + "}";
1084
    }
1085

    
1086

    
1087
    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
1088
        String url = request.getRequestURL().toString();
1089
        //String query = request.getQueryString();
1090

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

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

    
1109
    private String composeDataResponse(String xml) {
1110
        return " { \"status\" : \"success\", \"code\": \"200\", "
1111
                + "\"data\" : " + XML.toJSONObject(xml).toString() + " }";
1112
    }
1113

    
1114
    private String composeDataResponse(Claim claim) {
1115
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(claim) + " }";
1116
    }
1117

    
1118
    private String composeDataResponse(List<Notification> notifications) {
1119
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(notifications) + " }";
1120
    }
1121

    
1122
    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
1123
        logger.info("total " + total);
1124
        logger.info("currentOffset " + currentOffset);
1125
        logger.info("limit " + limit);
1126

    
1127
        String url = request.getRequestURL().toString();
1128
        //String query = request.getQueryString();
1129

    
1130
        String first = url+"?offset=0&limit=20";
1131

    
1132
        int previousPage;
1133
        int nextPage;
1134
        int lastPage;
1135

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

    
1147
        if (currentOffset-1 <= 0) {
1148
            previousPage = 0;
1149
        } else {
1150
            previousPage = currentOffset-1;
1151
        }
1152
        String previous = url+"?offset=" + previousPage + "&limit=20";
1153

    
1154
        if (currentOffset+1 >= lastPage) {
1155
            nextPage = lastPage;
1156

    
1157
        } else {
1158
            nextPage = currentOffset + 1;
1159
        }
1160
        String next = url+"?offset=" + nextPage + "&limit=20";
1161

    
1162
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + first +"\"}, {\"rel\":\"last\", \"href\":\"" + last + "\"}, {\"rel\":\"previous\", \"href\": \"" + previous + "\"}, {\"rel\":\"next\", \"href\":\"" +  next +"\"}"+ "]";
1163
    }
1164
    private String composeTotalResults(int total) {
1165
        return "\"total\": \""+total+"\"";
1166
    }
1167

    
1168
     public static void main(String[] args) {
1169

    
1170
/*
1171
         EmailValidator emailValidator = EmailValidator.getInstance();
1172
         System.out.println(emailValidator.isValid("jate@gdddd"));
1173

    
1174
         InternetAddress emailAddr = null;
1175
         try {
1176
             emailAddr = new InternetAddress("jate@gdddd");
1177
             emailAddr.validate();
1178
         } catch (AddressException e) {
1179
             System.out.println("false");
1180
         }
1181
         System.out.println("true");
1182

    
1183
         ArrayList<String> insertedIds= new ArrayList<String>();
1184
         insertedIds.add("1");
1185
         insertedIds.add("2");
1186
         insertedIds.add("3");
1187
         System.out.println(helloWorldService.compose403Message("hello"));
1188

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

    
1198
    }
1199

    
1200
//    @GET
1201
//    @Path("email-notifications")
1202
//    public void forceSendEmailNotifications() {
1203
//        emailSender.run();
1204
//    }
1205

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

    
1215
    private String getvalueOf(JsonObject jsonObject, String field){
1216
        String value = (jsonObject.get(field) != null && !jsonObject.get(field).isJsonNull())?jsonObject.get(field).getAsString():null;
1217
        logger.info(field + ": " + value);
1218
        return value;
1219

    
1220

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

    
1228
    private String getInfoAndBuildClaim(JsonObject jsonObject, String claimedBy ) throws SQLStoreException, Exception {
1229
        String claimedInDashboard = getvalueOfDefault(jsonObject, "claimedInDashboard", null);
1230

    
1231
        String sourceId = getvalueOf(jsonObject, "sourceId");
1232
        String sourceType = getvalueOf(jsonObject, "sourceType");
1233
        String sourceCollectedFrom = getvalueOf(jsonObject, "sourceCollectedFrom");
1234
        String sourceAccessRights = getvalueOf(jsonObject, "sourceAccessRights");
1235
        String sourceEmbargoEndDate = getvalueOfDefault(jsonObject, "sourceEmbargoEndDate", null);
1236

    
1237
        String targetId = getvalueOf(jsonObject, "targetId");
1238
        String targetType = getvalueOf(jsonObject, "targetType");
1239
        String targetCollectedFrom = getvalueOf(jsonObject, "targetCollectedFrom");
1240
        String targetAccessRights = getvalueOf(jsonObject, "targetAccessRights");
1241
        String targetEmbargoEndDate = getvalueOfDefault(jsonObject, "targetEmbargoEndDate", null);
1242

    
1243

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