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
                                     @CookieParam("openAIRESession") String  sessionId,
269
                                     @Context HttpServletRequest request) {
270
//        @RequestParam(value="includeStates[]", defaultValue="1,2,3") String[] includeStates
271

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

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

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

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

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

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

    
308

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

    
323

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

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

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

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

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

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

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

    
358

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

    
372

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

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

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

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

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

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

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

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

    
426

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

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

    
435
            List<Claim> claims = null;
436

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

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

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

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

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

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

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

    
485

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

    
488

    
489

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

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

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

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

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

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

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

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

    
529

    
530

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

    
537

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

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

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

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

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

    
593

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

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

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

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

    
613

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

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

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

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

    
642

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

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

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

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

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

    
666

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

    
677

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

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

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

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

    
725

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

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

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

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

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

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

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

    
793

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

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

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

    
819

    
820
            }
821
            if (jsonArray.size() == code500) {
822
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
823
                        .type(MediaType.APPLICATION_JSON).build();
824
            } else if (code200 > 0) {
825
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
826
            } else {
827
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
828
                        .type(MediaType.APPLICATION_JSON).build();
829
            }
830
        }
831
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
832
                .type(MediaType.APPLICATION_JSON)
833
                .build();
834

    
835
    }
836

    
837
    @GET
838
    @Path("/users/notification")
839
    @Produces(MediaType.APPLICATION_JSON)
840
    public Response getUserEmailNotificationPreferences(@QueryParam("communityId") String openaireId,
841
                                                        @HeaderParam("X-XSRF-TOKEN") String token,
842
                                                        @CookieParam("AccessToken") String  cookie,
843
                                                        @CookieParam("openAIRESession") String  sessionId,
844
                                                        @Context HttpServletRequest request) {
845

    
846
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
847
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
848
                    .type(MediaType.APPLICATION_JSON)
849
                    .build();
850
        }
851

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

    
857
            EmailValidator emailValidator = EmailValidator.getInstance();
858

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

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

    
869
            List<Notification> notifications = null;
870
            try {
871
                if(openaireId != null) {
872
//                    CommunityUtils communityInfo = this.emailSender.getCommunityUtils().getCommunityInfo(openaireId);
873
                    if(this.emailSender.getManagerUtils().isCommunityManager(openaireId, userMail, sessionId) || authorization.isCommunityCurator(userInfo)) {
874

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

    
879
                        if (notification != null) {
880
                            notifications = new ArrayList<Notification>();
881
                            notification.setOpenaireName(openaireId);
882
                            notifications.add(notification);
883
                        }
884
                    }else{
885
                        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
886
                                .type(MediaType.APPLICATION_JSON)
887
                                .build();
888
                    }
889
                } else {
890
                    Map<String, String> projectIdsAndNames = fetchProjectHandler.fetchProjectIdsAndNamesByProjectManagerMail(userMail);
891
                    if(projectIdsAndNames != null) {
892
                        for (Map.Entry<String, String> projectIdAndName : projectIdsAndNames.entrySet()) {
893
                            Notification notification = null;
894
                            logger.debug("About to fetch notification");
895
                            notification = fetchNotificationHandler.fetchNotification(projectIdAndName.getKey(), userMail);
896

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

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

    
919
            if (notifications == null || notifications.isEmpty()) {
920
                return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("There are no notifications for user with mail " + userMail)).type(MediaType.APPLICATION_JSON).build();
921
            }
922

    
923
            return Response.status(200).entity(composeDataResponse(notifications)).build();
924

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

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

    
942

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

    
957
            String userMail =userInfo.getEmail();
958

    
959
            String openaireId = jsonObject.get("openaireId").getAsString();
960
            logger.info("openaireId " + openaireId);
961

    
962
            boolean notify = jsonObject.get("notify").getAsBoolean();
963
            logger.info("notify "+notify);
964

    
965
            int frequency = jsonObject.get("frequency").getAsInt();
966
            logger.info("frequency " + frequency);
967

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

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

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

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

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

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

    
1032
    private  String compose200Message(String message){
1033
        return " { \"status\" : \"success\", \"code\": \"200\", \"message\" : \"  " + message +" \" }";
1034
    }
1035

    
1036
    private String compose204Message(String message) {
1037
        return  "{ \"status\" : \"error\", \"code\" : \"204\", \"message\" : \"  " + message +" \" }";
1038
    }
1039

    
1040
    private String compose400Message(String message) {
1041
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
1042
    }
1043

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

    
1049
    private String compose403Message(String message) {
1050
        return  "{ \"status\" : \"error\", \"code\" : \"403\", \"message\" : \"  " + message +"\", " +
1051
                "\"description\" : \"\" }";
1052
    }
1053

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

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

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

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

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

    
1082

    
1083

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

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

    
1093

    
1094
    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
1095
        String url = request.getRequestURL().toString();
1096
        //String query = request.getQueryString();
1097

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

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

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

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

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

    
1129
    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
1130
        logger.info("total " + total);
1131
        logger.info("currentOffset " + currentOffset);
1132
        logger.info("limit " + limit);
1133

    
1134
        String url = request.getRequestURL().toString();
1135
        //String query = request.getQueryString();
1136

    
1137
        String first = url+"?offset=0&limit=20";
1138

    
1139
        int previousPage;
1140
        int nextPage;
1141
        int lastPage;
1142

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

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

    
1161
        if (currentOffset+1 >= lastPage) {
1162
            nextPage = lastPage;
1163

    
1164
        } else {
1165
            nextPage = currentOffset + 1;
1166
        }
1167
        String next = url+"?offset=" + nextPage + "&limit=20";
1168

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

    
1175
    public static void main(String[] args) {
1176

    
1177
/*
1178
         EmailValidator emailValidator = EmailValidator.getInstance();
1179
         System.out.println(emailValidator.isValid("jate@gdddd"));
1180

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

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

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

    
1205
    }
1206

    
1207
//    @GET
1208
//    @Path("email-notifications")
1209
//    public void forceSendEmailNotifications() {
1210
//        emailSender.run();
1211
//    }
1212

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

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

    
1227

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

    
1235
    private String getInfoAndBuildClaim(JsonObject jsonObject, String claimedBy ) throws SQLStoreException, Exception {
1236
        String claimedInDashboard = getvalueOfDefault(jsonObject, "claimedInDashboard", null);
1237

    
1238
        String sourceId = getvalueOf(jsonObject, "sourceId");
1239
        String sourceType = getvalueOf(jsonObject, "sourceType");
1240
        String sourceCollectedFrom = getvalueOf(jsonObject, "sourceCollectedFrom");
1241
        String sourceAccessRights = getvalueOf(jsonObject, "sourceAccessRights");
1242
        String sourceEmbargoEndDate = getvalueOfDefault(jsonObject, "sourceEmbargoEndDate", null);
1243

    
1244
        String targetId = getvalueOf(jsonObject, "targetId");
1245
        String targetType = getvalueOf(jsonObject, "targetType");
1246
        String targetCollectedFrom = getvalueOf(jsonObject, "targetCollectedFrom");
1247
        String targetAccessRights = getvalueOf(jsonObject, "targetAccessRights");
1248
        String targetEmbargoEndDate = getvalueOfDefault(jsonObject, "targetEmbargoEndDate", null);
1249

    
1250

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