Project

General

Profile

1
package eu.dnetlib.openaire.rest;
2

    
3
import com.google.gson.*;
4
import eu.dnetlib.api.enabling.ISLookUpService;
5
import eu.dnetlib.api.enabling.ISLookUpServiceException;
6
import eu.dnetlib.data.claims.migration.ClaimValidationException;
7
import eu.dnetlib.data.claims.migration.entity.Claim;
8
import eu.dnetlib.data.claims.migration.handler.ClaimHandler;
9
import eu.dnetlib.data.claims.migration.handler.DirectIndexHandler;
10
import eu.dnetlib.data.claims.migration.handler.FetchClaimHandler;
11
import eu.dnetlib.data.claims.migration.handler.FetchProjectHandler;
12
import eu.dnetlib.data.claimsDemo.SQLStoreException;
13
import gr.uoa.di.driver.util.ServiceLocator;
14
import org.apache.commons.validator.EmailValidator;
15
import org.apache.log4j.Logger;
16
import org.json.XML;
17
import org.springframework.beans.factory.annotation.Autowired;
18
import org.springframework.stereotype.Component;
19

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

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

    
36
    private static final Logger logger = Logger.getLogger(HelloWorldService.class);
37

    
38
    @Autowired
39
    private FetchClaimHandler fetchClaimHandler = null;
40

    
41
    @Autowired
42
    private FetchProjectHandler fetchProjectHandler= null;
43

    
44
    @Resource
45
    private ServiceLocator<ISLookUpService> lookupServiceLocator = null;
46

    
47
    @Autowired
48
    private ClaimHandler claimHandler = null;
49

    
50
    @Autowired
51
    private DirectIndexHandler directIndexHandler = null;
52

    
53
    @Autowired
54
    public Authorization authorization = null;
55

    
56

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

    
71
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
72
            authorization.logStatus(token,cookie);
73
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
74
                    .type(MediaType.APPLICATION_JSON)
75
                    .build();
76
        }
77

    
78
        if(authorization.isClaimCurator(token)) {
79

    
80
            int total = -1;
81

    
82
            if (projectId == null || projectId.isEmpty()) {
83
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
84
                        .type(MediaType.APPLICATION_JSON).build();
85
            }
86

    
87
            List<Claim> claims = null;
88
            try {
89
                claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types,false);
90
                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
91

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

    
97
            }
98

    
99
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
100
        }
101

    
102
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
103
                .type(MediaType.APPLICATION_JSON)
104
                .build();
105
    }
106

    
107
    @GET
108
    @Path("project/claims")
109
    @Produces(MediaType.APPLICATION_JSON)
110
    public Response getProjectClaimsByToken(@QueryParam("projectToken") String projectToken,
111
                                     @DefaultValue("-1") @QueryParam("offset") int offset,
112
                                     @DefaultValue("-1") @QueryParam("limit") int limit,
113
                                     @DefaultValue("") @QueryParam("keyword") String keyword,
114
                                     @DefaultValue("") @QueryParam("sortby") String orderby,
115
                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
116
                                     @DefaultValue("") @QueryParam("types") List<String> types,
117
                                     @HeaderParam("X-XSRF-TOKEN") String token,
118
                                     @CookieParam("AccessToken") String  cookie,
119
                                     @Context HttpServletRequest request) {
120

    
121

    
122
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
123
            authorization.logStatus(token,cookie);
124
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
125
                    .type(MediaType.APPLICATION_JSON)
126
                    .build();
127
        }
128

    
129
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
130
//        if(authorization.isProjectCurator(userInfo)) {
131
            String userMail = userInfo.getEmail();
132

    
133
            int total = -1;
134

    
135
            if (projectToken == null || projectToken.isEmpty()) {
136
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project token cannot be empty."))
137
                        .type(MediaType.APPLICATION_JSON).build();
138
            }
139

    
140
            List<Claim> claims = null;
141
            try {
142
                String projectId = null;
143
                if(authorization.isProjectCurator(userInfo)) {
144
                    projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken);
145
                } else {
146
                    projectId = fetchProjectHandler.fetchProjectIdByTokenAndEmail(projectToken, userMail);
147
                }
148
                //String projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken,userMail);
149
                if(projectId == null){
150
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
151
                            .type(MediaType.APPLICATION_JSON)
152
                            .build();
153
                }else{
154
                    if(offset == -1 && limit == -1) {
155
                        // when offset and limit are -1 fetch claims with null values, to ignore paging and limit clause
156
                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, null, null, keyword, orderby, descending, types, true);
157
                    } else {
158
                        claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, types, true);
159
                    }
160
                    total = fetchClaimHandler.countClaimsByProject(projectId, keyword, types);
161

    
162
                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
163
                }
164

    
165
            } catch (SQLStoreException|Exception e) {
166
                logger.error("Could not fetch claims for project token " + projectToken, e);
167
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
168
                        " for projects with token " + projectToken + ".", e)).type(MediaType.APPLICATION_JSON).build();
169
            }
170
//        }
171

    
172
//        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
173
//                .type(MediaType.APPLICATION_JSON)
174
//                .build();
175
    }
176
    @GET
177
    @Path("/contexts/{contextId}/claims")
178
    @Produces(MediaType.APPLICATION_JSON)
179
    public Response getContextClaims(@PathParam("contextId") String contextId,
180
                           @DefaultValue("0") @QueryParam("offset") int offset,
181
                           @DefaultValue("20") @QueryParam("limit") int limit,
182
                           @DefaultValue("") @QueryParam("keyword") String keyword,
183
                           @DefaultValue("") @QueryParam("sortby") String orderby,
184
                           @DefaultValue("true") @QueryParam("descending") boolean descending,
185
                           @DefaultValue("") @QueryParam("types") List<String> types,
186
                                     @HeaderParam("X-XSRF-TOKEN") String token,
187
                                     @CookieParam("AccessToken") String  cookie,
188
                                     @Context HttpServletRequest request) {
189
//        @RequestParam(value="includeStates[]", defaultValue="1,2,3") String[] includeStates
190

    
191
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
192
            authorization.logStatus(token,cookie);
193
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
194
                    .type(MediaType.APPLICATION_JSON)
195
                    .build();
196
        }
197
//        logger.debug("Calling API for context with token " + token);
198

    
199
        if(authorization.isCommunityCurator(token) || authorization.isClaimCurator(token)) {
200

    
201
            int total = -1;
202
            if (contextId == null || contextId.isEmpty()) {
203
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
204
                        .type(MediaType.APPLICATION_JSON).build();
205
            }
206
            logger.debug("Types are " + types);
207
            List<Claim> claims = null;
208

    
209
            try {
210
                claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset, keyword, orderby, descending, types,false);
211
                total = fetchClaimHandler.countClaimsByContext(contextId, keyword, types);
212

    
213
            } catch (SQLStoreException|Exception e) {
214
                logger.error("Could not fetch claims for context with id " + contextId, e);
215
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
216
                        " for context with id " + contextId + ".", e)).type(MediaType.APPLICATION_JSON).build();
217
            }
218

    
219
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
220
        }
221

    
222
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
223
                .type(MediaType.APPLICATION_JSON)
224
                .build();
225
    }
226

    
227

    
228
    @GET
229
    @Path("/results/{resultId}/claims")
230
    @Produces(MediaType.APPLICATION_JSON)
231
    public Response getResultClaims(@PathParam("resultId") String resultId,
232
                                    @DefaultValue("0") @QueryParam("offset") int offset,
233
                                    @DefaultValue("20") @QueryParam("limit") int limit,
234
                                    @DefaultValue("") @QueryParam("keyword") String keyword,
235
                                    @DefaultValue("") @QueryParam("sortby") String orderby,
236
                                    @DefaultValue("true") @QueryParam("descending") boolean descending,
237
                                    @DefaultValue("") @QueryParam("types") List<String> types,
238
                                    @HeaderParam("X-XSRF-TOKEN") String token,
239
                                    @CookieParam("AccessToken") String  cookie,
240
                                    @Context HttpServletRequest request) {
241

    
242

    
243
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
244
            authorization.logStatus(token,cookie);
245
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
246
                    .type(MediaType.APPLICATION_JSON)
247
                    .build();
248
        }
249

    
250
        if(authorization.isClaimCurator(token)) {
251

    
252
            int total = -1;
253
            if (resultId == null || resultId.isEmpty()) {
254
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
255
                        .type(MediaType.APPLICATION_JSON).build();
256
            }
257

    
258
            List<Claim> claims = null;
259
            try {
260
                claims = fetchClaimHandler.fetchClaimsByResult(resultId, limit, offset, keyword, orderby, descending, types,false);
261
                total = fetchClaimHandler.countClaimsByResult(resultId, keyword, types);
262

    
263
            } catch (SQLStoreException|Exception e) {
264
                logger.error("Could not fetch claims for result with id " + resultId, e);
265
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
266
                        " for result with id " + resultId + ".", e)).type(MediaType.APPLICATION_JSON).build();
267
            }
268

    
269
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
270
        }
271

    
272
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
273
                .type(MediaType.APPLICATION_JSON)
274
                .build();
275
    }
276

    
277

    
278
    @GET
279
    @Path("/users/claims")
280
    @Produces(MediaType.APPLICATION_JSON)
281
    public Response getUserClaims(@DefaultValue("0") @QueryParam("offset") int offset,
282
                                  @DefaultValue("20") @QueryParam("limit") int limit,
283
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
284
                                  @DefaultValue("") @QueryParam("sortby") String orderby,
285
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
286
                                  @DefaultValue("") @QueryParam("types") List<String> types,
287
                                  @HeaderParam("X-XSRF-TOKEN") String token,
288
                                  @CookieParam("AccessToken") String  cookie,
289
                                  @Context HttpServletRequest request) {
290

    
291

    
292
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
293
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
294
                    .type(MediaType.APPLICATION_JSON)
295
                    .build();
296
        }
297

    
298
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
299
        if(authorization.isRegistered(userInfo)) {
300
            String userMail = userInfo.getEmail();
301
            logger.debug("User is registerd "  );
302
            int total = -1;
303
            EmailValidator emailValidator = EmailValidator.getInstance();
304

    
305
            if (userMail == null || userMail.isEmpty()) {
306
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
307
                        .type(MediaType.APPLICATION_JSON).build();
308
            }
309

    
310
            if (!emailValidator.isValid(userMail)) {
311
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
312
                        .type(MediaType.APPLICATION_JSON).build();
313
            }
314

    
315
            List<Claim> claims = null;
316
            try {
317
                logger.debug("About to fetch claims"  );
318
                claims = fetchClaimHandler.fetchClaimsByUser(userMail, limit, offset, keyword, orderby, descending, types,false);
319
                total = fetchClaimHandler.countClaimsByUser(userMail, keyword, types);
320

    
321
            } catch (SQLStoreException|Exception e) {
322
                logger.error("Could not fetch claims for user with mail " + userMail, e);
323
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
324
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
325
            }
326

    
327
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
328
        }
329
        logger.debug("User is *NOT* registerd "  );
330
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
331
                .type(MediaType.APPLICATION_JSON)
332
                .build();
333
    }
334

    
335
    @GET
336
    @Path("/claims/{claimId}")
337
    @Produces(MediaType.APPLICATION_JSON)
338
    public Response getClaimsById(@PathParam("claimId") String claimId,
339
                                  @DefaultValue("0") @QueryParam("offset") int offset,
340
                                  @DefaultValue("20") @QueryParam("limit") int limit,
341
                                  @HeaderParam("X-XSRF-TOKEN") String token,
342
                                  @CookieParam("AccessToken") String  cookie,
343
                                  @Context HttpServletRequest request) {
344

    
345

    
346
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
347
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
348
                    .type(MediaType.APPLICATION_JSON)
349
                    .build();
350
        }
351

    
352
        if(authorization.isRegistered(token)) {
353

    
354
            List<Claim> claims = null;
355

    
356
            int total = -1;
357
            if (claimId == null || claimId.isEmpty()) {
358
                try {
359
                    claims = fetchClaimHandler.fetchAllClaims(limit, offset,false);
360
                    total = fetchClaimHandler.countAllClaims("", new ArrayList<String>());
361

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

    
364
                } catch (SQLStoreException|Exception e) {
365
                    logger.error("Could not fetch claims.", e);
366
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
367
                            .type(MediaType.APPLICATION_JSON).build();
368
                }
369
            }
370

    
371
            try {
372
                Claim claim = fetchClaimHandler.fetchClaimById(claimId,false);
373
                if (claim == null) {
374
                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Cannot find claim with id " + claimId + "."))
375
                            .type(MediaType.APPLICATION_JSON).build();
376
                }
377

    
378
                return Response.status(200).entity(composeDataResponse(claim)).build();
379

    
380
            } catch (SQLStoreException|Exception e) {
381
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claim " +
382
                        "with id " + claimId + " id.", e)).type(MediaType.APPLICATION_JSON).build();
383
            }
384
        }
385
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
386
                .type(MediaType.APPLICATION_JSON)
387
                .build();
388
    }
389

    
390
    @GET
391
    @Path("/claims")
392
    @Produces(MediaType.APPLICATION_JSON)
393
    public Response getAllClaims(@DefaultValue("0") @QueryParam("offset") int offset,
394
                                  @DefaultValue("20") @QueryParam("limit") int limit,
395
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
396
                                  @DefaultValue("date") @QueryParam("sortby") String orderby,
397
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
398
                                  @DefaultValue("") @QueryParam("types") List<String> types,
399
                                 @HeaderParam("X-XSRF-TOKEN") String token,
400
                                 @HeaderParam("Origin") String origin,
401
                                 @CookieParam("AccessToken") String  cookie,
402
                                  @Context HttpServletRequest request) {
403

    
404

    
405
        logger.debug("Header  \"Origin\" has value  " + origin);
406

    
407

    
408

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

    
412
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
413
                    .type(MediaType.APPLICATION_JSON)
414
                    .build();
415
        }
416

    
417
        if(authorization.isClaimCurator(token)) {
418
            logger.debug("User is authorized ! !");
419
            List<Claim> claims = null;
420

    
421
            int total = -1;
422
            try {
423
                claims = fetchClaimHandler.fetchAllClaims(limit, offset, keyword, orderby, descending, types,false);
424
                total = fetchClaimHandler.countAllClaims(keyword, types);
425

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

    
428
            } catch (SQLStoreException|Exception e) {
429
                logger.error("Could not fetch claims.", e);
430
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
431
                        .type(MediaType.APPLICATION_JSON).build();
432
            }
433
        }
434

    
435
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
436
               .type(MediaType.APPLICATION_JSON)
437
               .build();
438
    }
439

    
440
    //ARGIRO TODO: Na thn tsekarw
441
//    @POST
442
//    @Path("/claims/{claimId}")
443
//    @Produces(MediaType.APPLICATION_JSON)
444
//    public Response deleteClaim(@PathParam("claimId") String claimId,
445
//                                @QueryParam("token") String token) {
446
//
447
//        if(!JWTValidator.isValid(token)) {
448
//            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
449
//                    .type(MediaType.APPLICATION_JSON)
450
//                    .build();
451
//        }
452
//        try {
453
//
454
//            if (authorization.isRegistered(token) && (authorization.getUserHandler().getMail(token).equals(fetchClaimHandler.fetchClaimById(claimId).getUserMail()))) {
455
//                if (claimId == null || claimId.isEmpty()) {
456
//                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
457
//                            .type(MediaType.APPLICATION_JSON).build();
458
//                }
459
//
460
//                try {
461
//                    if (claimHandler.deleteClaim(claimId)) {
462
//                        return Response.status(204).entity(compose204Message()).type(MediaType.APPLICATION_JSON).build();
463
//                    }
464
//
465
//                } catch (Exception e) {
466
//                    logger.error("Fail to delete claim with id " + claimId + ".", e);
467
//                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId + ".", e))
468
//                            .type(MediaType.APPLICATION_JSON).build();
469
//                }
470
//
471
//                return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
472
//                        .type(MediaType.APPLICATION_JSON).build();
473
//            }
474
//
475
//            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
476
//                    .type(MediaType.APPLICATION_JSON)
477
//                    .build();
478
//
479
//        } catch (Exception e) {
480
//            logger.error("Could not fetch claims.", e);
481
//            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
482
//                    .type(MediaType.APPLICATION_JSON).build();
483
//        }
484
//    }
485
/*
486

    
487
    @DELETE
488
    @Path("/claims/{claimId}")
489
    public Response deleteClaim(@PathParam("claimId") String claimId) {
490

    
491
        if (claimId == null || claimId.isEmpty()) {
492
            return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
493
                    .header("Access-Control-Allow-Methods", "DELETE")
494
                    .type(MediaType.APPLICATION_JSON).build();
495
        }
496

    
497
        try {
498
            if(claimHandler.deleteClaim(claimId)) {
499
                return Response.status(204).entity(compose204Message()).header("Access-Control-Allow-Origin", "*")
500
                        .header("Access-Control-Allow-Methods", "DELETE").type(MediaType.APPLICATION_JSON).build();
501
            }
502

    
503
        } catch (Exception e) {return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
504
                    .type(MediaType.APPLICATION_JSON)
505
                    .build();
506
            logger.error("Fail to delete claim with id " + claimId + ".", e);
507
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId +".", e))
508
                    .header("Access-Control-Allow-Origin", "*")
509
                    .header("Access-Control-Allow-Methods", "DELETE")
510
                    .type(MediaType.APPLICATION_JSON).build();
511
        }
512

    
513
        return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
514
                .header("Access-Control-Allow-Methods", "DELETE")
515
                .type(MediaType.APPLICATION_JSON).build();
516
    }
517
 */
518
    @DELETE
519
    @Path("/claims/bulk")
520
    @Produces(MediaType.APPLICATION_JSON)
521
    public Response deleteBulkClaims(@QueryParam("claimId") List<String> claimIds,
522
                                     @HeaderParam("X-XSRF-TOKEN") String token,
523
                                     @HeaderParam("Origin") String origin,
524
                                     @CookieParam("AccessToken") String  cookie){
525

    
526

    
527

    
528
         if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
529
             return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
530
                     .type(MediaType.APPLICATION_JSON)
531
                     .build();
532
         }
533

    
534

    
535
        ArrayList<String> deletedIds= new ArrayList<String>();
536
        ArrayList<String> notFoundIds= new ArrayList<String>();
537

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

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

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

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

    
590

    
591
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token) || !authorization.hasValidOrigin(origin)){
592
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
593
                    .type(MediaType.APPLICATION_JSON)
594
                    .build();
595
        }
596

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

    
601
            String claimedBy = userInfo.getEmail();
602
            logger.info("claimedBy " + claimedBy);
603

    
604
            String sourceId = jsonObject.get("sourceId").getAsString();
605
            logger.info("sourceId " + sourceId);
606
            String sourceType = jsonObject.get("sourceType").getAsString();
607
            logger.info("sourceType " + sourceType);
608
            String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
609
            logger.info("sourceCollectedFrom " + sourceCollectedFrom);
610
            String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
611
            logger.info("sourceAccessRights " + sourceAccessRights);
612
            String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
613
            sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
614
            logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
615

    
616
            String targetId = jsonObject.get("targetId").getAsString();
617
            logger.info("targetId " + targetId);
618
            String targetType = jsonObject.get("targetType").getAsString();
619
            logger.info("targetType " + targetType);
620
            String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
621
            logger.info("targetCollectedFrom " + targetCollectedFrom);
622
            String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
623
            logger.info("targetAccessRights " + targetAccessRights);
624
            String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
625
            targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
626
            logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
627

    
628
            EmailValidator emailValidator = EmailValidator.getInstance();
629
            if (!emailValidator.isValid(claimedBy)) {
630
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
631
                        .type(MediaType.APPLICATION_JSON).build();
632
            }
633

    
634

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

    
639
            } catch (ClaimValidationException ve) {
640
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
641
                        .type(MediaType.APPLICATION_JSON).build();
642

    
643
            } catch (SQLStoreException|Exception e) {
644
                logger.error("Fail to add new claim.", e);
645
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
646
                        .type(MediaType.APPLICATION_JSON).build();
647
            }
648
        }
649
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access."))
650
                .type(MediaType.APPLICATION_JSON)
651
                .build();
652
    }
653

    
654
    @POST
655
    @Path("/claims/bulk")
656
    @Produces(MediaType.APPLICATION_JSON)
657
    @Consumes(MediaType.APPLICATION_JSON)
658
    public Response addBulkClaims(String input, @Context HttpServletRequest request,
659
                                  @HeaderParam("X-XSRF-TOKEN") String token,
660
                                  @HeaderParam("Origin") String origin,
661
                                  @CookieParam("AccessToken") String  cookie) {
662

    
663

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

    
670
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
671
        if(authorization.isRegistered(userInfo)) {
672
            ArrayList<String> insertedIds = new ArrayList<String>();
673
            JsonArray errorInClaims = new JsonArray();
674

    
675
            int code200 = 0;
676
            int code400 = 0;
677
            int code500 = 0;
678

    
679
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
680
            for (JsonElement je : jsonArray) {
681
                JsonObject jsonObject = je.getAsJsonObject();
682

    
683
                logger.info("targetId " + jsonObject.toString());
684
                String claimedBy = userInfo.getEmail();
685
                logger.info("claimedBy " + claimedBy);
686

    
687
                String sourceId = jsonObject.get("sourceId").getAsString();
688
                logger.info("sourceId " + sourceId);
689
                String sourceType = jsonObject.get("sourceType").getAsString();
690
                logger.info("sourceType " + sourceType);
691
                String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
692
                logger.info("sourceCollectedFrom " + sourceCollectedFrom);
693
                String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
694
                logger.info("sourceAccessRights " + sourceAccessRights);
695
                String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
696
                sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
697
                logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
698

    
699
                String targetId = jsonObject.get("targetId").getAsString();
700
                logger.info("targetId " + targetId);
701
                String targetType = jsonObject.get("targetType").getAsString();
702
                logger.info("targetType " + targetType);
703
                String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
704
                logger.info("targetCollectedFrom " + targetCollectedFrom);
705
                String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
706
                logger.info("targetAccessRights " + targetAccessRights);
707
                String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
708
                targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
709
                logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
710

    
711
                EmailValidator emailValidator = EmailValidator.getInstance();
712
                if (!emailValidator.isValid(claimedBy)) {
713
                    jsonObject.addProperty("error", "user");
714
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
715
                    //                        .type(MediaType.APPLICATION_JSON).build();
716
                    code400++;
717
                    errorInClaims.add(jsonObject);
718
                }
719

    
720

    
721
                try {
722
                    String claimId = claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate);
723
                    insertedIds.add(claimId);
724
                    code200++;
725
                    //                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
726

    
727
                } catch (ClaimValidationException ve) {
728
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
729
                    //                        .type(MediaType.APPLICATION_JSON).build();
730
                    jsonObject.addProperty("error", "validation");
731
                    errorInClaims.add(jsonObject);
732
                    code400++;
733

    
734
                } catch (SQLStoreException|Exception e) {
735
                    //                logger.error("Fail to add new claim.", e);
736
                    //                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
737
                    //                        .type(MediaType.APPLICATION_JSON).build();
738
                    jsonObject.addProperty("error", "insertion");
739
                    errorInClaims.add(jsonObject);
740
                    code500++;
741
                }
742
            }
743
            if (jsonArray.size() == code500) {
744
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
745
                        .type(MediaType.APPLICATION_JSON).build();
746
            } else if (code200 > 0) {
747
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
748
            } else {
749
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
750
                        .type(MediaType.APPLICATION_JSON).build();
751
            }
752
        }
753
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
754
                .type(MediaType.APPLICATION_JSON)
755
                .build();
756

    
757
    }
758
    @POST
759
    @Path("/curate/bulk")
760
    @Produces(MediaType.APPLICATION_JSON)
761
    @Consumes(MediaType.APPLICATION_JSON)
762
    public Response curateBulkClaims(String input, @Context HttpServletRequest request,
763
                                     @HeaderParam("X-XSRF-TOKEN") String token,
764
                                     @HeaderParam("Origin") String origin,
765
                                     @CookieParam("AccessToken") String  cookie) {
766

    
767

    
768
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)|| !authorization.hasValidOrigin(origin)){
769
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
770
                    .type(MediaType.APPLICATION_JSON)
771
                    .build();
772
        }
773
        UserInfo userInfo = authorization.getUserHandler().getUserInfo(token);
774
        if (authorization.isRegistered(userInfo)) {
775
            ArrayList<String> insertedIds = new ArrayList<String>();
776
            JsonArray errorInClaims = new JsonArray();
777
            int code200 = 0;
778
            int code400 = 0;
779
            int code500 = 0;
780
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
781
            String curatedBy =userInfo.getEmail();
782

    
783
            for (JsonElement je : jsonArray) {
784
                JsonObject jsonObject = je.getAsJsonObject();
785

    
786
                 String id = jsonObject.get("id").getAsString();
787
                logger.info("id " + id);
788

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

    
800
                try {
801
                    claimHandler.updateClaimCurationInfo(curatedBy,id, approved);
802
                    insertedIds.add(id);
803
                    code200++;
804

    
805
                } catch (SQLStoreException|Exception e) {
806
                    jsonObject.addProperty("error", "insertion");
807
                    errorInClaims.add(jsonObject);
808
                    code500++;
809
                }
810
            }
811
            if (jsonArray.size() == code500) {
812
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to update claims.", insertedIds, errorInClaims))
813
                        .type(MediaType.APPLICATION_JSON).build();
814
            } else if (code200 > 0) {
815
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
816
            } else {
817
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
818
                        .type(MediaType.APPLICATION_JSON).build();
819
            }
820
        }
821
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
822
                .type(MediaType.APPLICATION_JSON)
823
                .build();
824

    
825
    }
826
    @POST
827
    @Path("/feed/bulk")
828
    @Produces(MediaType.APPLICATION_JSON)
829
    @Consumes(MediaType.APPLICATION_JSON)
830
    public Response feedBulkRecords(String input, @Context HttpServletRequest request,
831
                                    @HeaderParam("X-XSRF-TOKEN") String token,
832
                                    @HeaderParam("Origin") String origin,
833
                                    @CookieParam("AccessToken") String  cookie) {
834

    
835

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

    
838
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
839
                    .type(MediaType.APPLICATION_JSON)
840
                    .build();
841
        }
842

    
843
        if (authorization.isRegistered(token)) {
844
            ArrayList<String> insertedIds = new ArrayList<String>();
845
            JsonArray errorInClaims = new JsonArray();
846
            int code200 = 0;
847
            int code400 = 0;
848
            int code500 = 0;
849
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
850
            for (JsonElement je : jsonArray) {
851
                JsonObject jsonObject = je.getAsJsonObject();
852
                Boolean inserted = directIndexHandler.insertRecord(new Gson().toJson(jsonObject.get("record")));
853
                if (inserted) {
854
                    insertedIds.add(jsonObject.get("id").getAsString());
855
                    code200++;
856
                } else {
857
                    errorInClaims.add(jsonObject.get("id").getAsString());
858
                    code400++;
859
                }
860

    
861

    
862
            }
863
            if (jsonArray.size() == code500) {
864
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
865
                        .type(MediaType.APPLICATION_JSON).build();
866
            } else if (code200 > 0) {
867
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
868
            } else {
869
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
870
                        .type(MediaType.APPLICATION_JSON).build();
871
            }
872
        }
873
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
874
                .type(MediaType.APPLICATION_JSON)
875
                .build();
876

    
877
    }
878

    
879
    @Path("/communities")
880
    @GET
881
    @Produces(MediaType.APPLICATION_JSON)
882
    public Response fetchCommunities(@HeaderParam("X-XSRF-TOKEN") String token,
883
                                     @CookieParam("AccessToken") String  cookie) throws ISLookUpServiceException {
884

    
885

    
886
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
887
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
888
                    .type(MediaType.APPLICATION_JSON)
889
                    .build();
890
        }
891

    
892
        if (authorization.isRegistered(token)) {
893
            //it needs to have at lease one category with @claim=true
894
            List<String> communities = lookupServiceLocator.getService().quickSearchProfile
895
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')  \n" +
896
                            "                where $x//context[@type='community']//category[@claim='true'] \n" +
897
                            "            return <communities>{$x//context/@id}{$x//context/@label}</communities>");
898

    
899
            return Response.status(200).entity(composeDataResponse(xml2Json(communities))).type(MediaType.APPLICATION_JSON).build();
900
        }
901
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
902
                .type(MediaType.APPLICATION_JSON)
903
                .build();
904
    }
905

    
906
    @Path("/communities/{communityid}/categories")
907
    @GET
908
    @Produces(MediaType.APPLICATION_JSON)
909
    public Response fetchCommunityCategories(@PathParam("communityid") String communityid,
910
                                             @HeaderParam("X-XSRF-TOKEN") String token,
911
                                             @CookieParam("AccessToken") String  cookie) throws ISLookUpServiceException {
912

    
913

    
914
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
915
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
916
                    .type(MediaType.APPLICATION_JSON)
917
                    .build();
918
        }
919

    
920
        if (authorization.isRegistered(token)) {
921
            List<String> categories = lookupServiceLocator.getService().quickSearchProfile
922
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')//context[@id='" + communityid + "']//category[@claim=\'true\']\n" +
923
                            "return <category>{$x/@id}{$x/@label}</category>");
924

    
925
            logger.info("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')//context[@id='" + communityid + "']//category[@claim=\'true\']\n" +
926
                    "return <category>{$x/@id}{$x/@label}</category>");
927

    
928
            if (categories == null || categories.isEmpty()) {
929
                return Response.status(404).entity(compose404Message("There are no categories for community with id " + communityid)).type(MediaType.APPLICATION_JSON).build();
930
            }
931

    
932
            xml2Json(categories);
933

    
934
            return Response.status(200).entity(composeDataResponse(xml2Json(categories))).type(MediaType.APPLICATION_JSON).build();
935
        }
936
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
937
                .type(MediaType.APPLICATION_JSON)
938
                .build();
939
    }
940

    
941
    @Path("/categories/{categoryid}/concepts")
942
    @GET
943
    @Produces(MediaType.APPLICATION_JSON)
944
    public Response fetchCategoryConcepts(@PathParam("categoryid") String categoryid,
945
                                          @HeaderParam("X-XSRF-TOKEN") String token,
946
                                          @CookieParam("AccessToken") String  cookie) throws ISLookUpServiceException {
947

    
948

    
949
        if(token == null || token.isEmpty() || cookie == null || cookie.isEmpty() || !cookie.equals(token)){
950
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
951
                    .type(MediaType.APPLICATION_JSON)
952
                    .build();
953
        }
954

    
955
        if (authorization.isRegistered(token)) {
956
            List<String> concepts = lookupServiceLocator.getService().quickSearchProfile
957
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType') return $x//category[@id='" + categoryid + "']//concept");
958

    
959
            if (concepts == null || concepts.isEmpty()) {
960
                return Response.status(404).entity(compose404Message("There are no concepts for category with id " + categoryid)).type(MediaType.APPLICATION_JSON).build();
961
            }
962

    
963
            return Response.status(200).entity(composeDataResponse(xml2Json(concepts))).type(MediaType.APPLICATION_JSON).build();
964
        }
965
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
966
                .type(MediaType.APPLICATION_JSON)
967
                .build();
968
    }
969

    
970
    private String xml2Json(List<String> input) {
971
        StringBuilder builder = new StringBuilder();
972
        for(String category: input) {
973
            builder.append(category);
974
        }
975
        return builder.toString();
976
    }
977

    
978
    private String compose400Message(String message) {
979
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
980
    }
981

    
982
    private String compose400Message(String message, Exception exception) {
983
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
984
                "\"description\" : \""+  exception.getMessage() +"\" }";
985
    }
986

    
987
    private String compose403Message(String message) {
988
        return  "{ \"status\" : \"error\", \"code\" : \"403\", \"message\" : \"  " + message +"\", " +
989
                "\"description\" : \"\" }";
990
    }
991

    
992
    private String compose404BulkDeleteMessage(String message, List<String> deletedIds, List<String> notFoundIds) {
993
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \","+  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
994
    }
995
    private String compose404Message(String message) {
996
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
997
    }
998

    
999
    private String compose400BulkInsertMessage(String message, List<String> insertedIds,JsonArray errorInClaims) {
1000
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \""+  ", \"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1001
    }
1002

    
1003
    private String compose500Message(String message, Throwable throwable) {
1004
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1005
                "\"description\" : \""+  throwable.getMessage() +"\" }";
1006
    }
1007

    
1008
    private String compose500BulkInsertMessage(String message,  List<String> insertedIds, JsonArray errorInClaims) {
1009
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1010
                "\"description\" : \""+   "\" , " +  "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
1011
    }
1012

    
1013
    /*
1014
    TODO check if needed
1015
    private String compose500BulkDeleteMessage(String message,  List<String> deletedIds, List<String> notFoundIds, Exception exception) {
1016
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
1017
                "\"description\" : \""+  exception.getMessage() +"\" ," +  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
1018
    }
1019

    
1020
    TODO check if needed
1021
    private  String compose200Message(){
1022
        return " { \"status\" : \"success\", \"code\": \"200\" }";
1023
    }
1024

    
1025
    TODO check if needed
1026
    private  String compose204Message(){
1027
        return " { \"status\" : \"success\", \"code\": \"204\" }";
1028
    } */
1029

    
1030
    private  String compose204BulkDeleteMessage(List<String> deletedIds, List<String> notFoundIds){
1031
        return " { \"status\" : \"success\", \"code\": \"204\", "+ "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + "}";
1032
    }
1033

    
1034

    
1035
    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
1036
        String url = request.getRequestURL().toString();
1037
        //String query = request.getQueryString();
1038

    
1039
        return " { \"status\" : \"success\", \"code\": \"201\", \"link\": \"" + url  +"/"+ claimId +"\" }";
1040
    }
1041
    private  String compose201BulkInsertMessage(List<String> insertedIds, JsonArray errorInClaims){
1042
        //String url = request.getRequestURL().toString();
1043
        //String query = request.getQueryString();
1044

    
1045
        return " { \"status\" : \"success\", \"code\": \"201\","+ "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims)+ "}";
1046
    }
1047
    private String composeDataResponse(HttpServletRequest request, List<Claim> claims, int total, int offset, int limit) {
1048
        if(offset != -1 && limit != -1) {   // if offset and limit are -1, no paging in the response
1049
            return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", " + composePaging(request, total, offset, limit) + ", "
1050
                    + "\"data\" : " + new Gson().toJson(claims) + " }";
1051
        } else {
1052
            return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", "
1053
                    + "\"data\" : " + new Gson().toJson(claims) + " }";
1054
        }
1055
    }
1056

    
1057
    private String composeDataResponse(String xml) {
1058
        return " { \"status\" : \"success\", \"code\": \"200\", "
1059
                + "\"data\" : " + XML.toJSONObject(xml).toString() + " }";
1060
    }
1061

    
1062
    private String composeDataResponse(Claim claim) {
1063
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(claim) + " }";
1064
    }
1065

    
1066
    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
1067
        logger.info("total " + total);
1068
        logger.info("currentOffset " + currentOffset);
1069
        logger.info("limit " + limit);
1070

    
1071
        String url = request.getRequestURL().toString();
1072
        //String query = request.getQueryString();
1073

    
1074
        String first = url+"?offset=0&limit=20";
1075

    
1076
        int previousPage;
1077
        int nextPage;
1078
        int lastPage;
1079

    
1080
        if (total <= limit) {
1081
            lastPage = 0;
1082
        } else {
1083
            if(total%limit == 0) {
1084
                lastPage = total/limit-1;
1085
            } else {
1086
                lastPage = total/limit ;
1087
            }
1088
        }
1089
        String last = url+"?offset=" + lastPage + "&limit=20";
1090

    
1091
        if (currentOffset-1 <= 0) {
1092
            previousPage = 0;
1093
        } else {
1094
            previousPage = currentOffset-1;
1095
        }
1096
        String previous = url+"?offset=" + previousPage + "&limit=20";
1097

    
1098
        if (currentOffset+1 >= lastPage) {
1099
            nextPage = lastPage;
1100

    
1101
        } else {
1102
            nextPage = currentOffset + 1;
1103
        }
1104
        String next = url+"?offset=" + nextPage + "&limit=20";
1105

    
1106
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + first +"\"}, {\"rel\":\"last\", \"href\":\"" + last + "\"}, {\"rel\":\"previous\", \"href\": \"" + previous + "\"}, {\"rel\":\"next\", \"href\":\"" +  next +"\"}"+ "]";
1107
    }
1108
    private String composeTotalResults(int total) {
1109
        return "\"total\": \""+total+"\"";
1110
    }
1111

    
1112
     public static void main(String[] args) {
1113

    
1114
/*
1115
         EmailValidator emailValidator = EmailValidator.getInstance();
1116
         System.out.println(emailValidator.isValid("jate@gdddd"));
1117

    
1118
         InternetAddress emailAddr = null;
1119
         try {
1120
             emailAddr = new InternetAddress("jate@gdddd");
1121
             emailAddr.validate();
1122
         } catch (AddressException e) {
1123
             System.out.println("false");
1124
         }
1125
         System.out.println("true");
1126

    
1127
         ArrayList<String> insertedIds= new ArrayList<String>();
1128
         insertedIds.add("1");
1129
         insertedIds.add("2");
1130
         insertedIds.add("3");
1131
         System.out.println(helloWorldService.compose403Message("hello"));
1132

    
1133
*/
1134
//         BasicConfigurator.configure();
1135
//         ApplicationContext context = new ClassPathXmlApplicationContext("eu/dnetlib/openaire/rest/springContext-claims-authorization.xml");
1136
//
1137
//         Authorization authorization =  context.getBean(Authorization.class);
1138
//         UserHandler userHandler = context.getBean(UserHandler.class);
1139
//         System.out.println(authorization.getAdminRoles());
1140
//         authorization.isClaimCurator("eyJraWQiOiJvaWRjIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwOTMxNzMwMTMyODMzNjMyQG9wZW5taW50ZWQuZXUiLCJhenAiOiIyNGU4MzE3Ni0xMzEyLTRiYTMtYmMwYi1mZmVlYmVhMTYwM2UiLCJpc3MiOiJodHRwczpcL1wvYWFpLm9wZW5taW50ZWQuZXVcL29pZGNcLyIsImV4cCI6MTQ5ODQ4NTk3NiwiaWF0IjoxNDk4NDcxNTc2LCJqdGkiOiJkMWRlZjc1Yi00MTEyLTRiZDktYTIyNi0wZThhOWI2M2Y3MWQifQ.WVYOb_yO8OaxIIt2jRYEDQBhGGFRDTBw3DgtVV_smuN5yx1ScCj6aehLu3JKPSArme4m2SGF4TEGhpwNJkwhM2WapGtxmtuCmCzYIo_QlC1Yki9hr2OT2rXMcQsJCiKaBSf6pLue6Sn78GMB5yaUTvOQHRgidXGiZXH5lsuZUx15Q6Equ_wzond_rgP9mRheRkTyIFuvvg4PuzmudBc11Ty863vIIQtoWF7_p98zTbHxiNF9lLPwzPZKxDoQ8JeayQEC-jsWVLgxmp-h0jG_Ko5jFVVJeeosqMMucOrs2FT_NKHVYVqB6VVh0C6nOufeiLrNDeMUlDT4dAvKD2zE9w");
1141

    
1142
    }
1143

    
1144
}
(2-2/3)