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.FetchClaimHandler;
10
import eu.dnetlib.openaire.rest.authorization.Authorization;
11
import eu.dnetlib.openaire.rest.security.JWTValidator;
12
import gr.uoa.di.driver.util.ServiceLocator;
13
import org.apache.commons.validator.EmailValidator;
14
import org.apache.log4j.Logger;
15
import org.json.JSONObject;
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
    @Resource
42
    private ServiceLocator<ISLookUpService> lookupServiceLocator = null;
43

    
44
    @Autowired
45
    private ClaimHandler claimHandler = null;
46

    
47

    
48
    @GET
49
    @Path("projects/{projectId}/claims")
50
    @Produces(MediaType.APPLICATION_JSON)
51
    public Response getProjectClaims(@PathParam("projectId") String projectId,
52
                           @DefaultValue("0") @QueryParam("offset") int offset,
53
                           @DefaultValue("20") @QueryParam("limit") int limit,
54
                           @DefaultValue("") @QueryParam("keyword") String keyword,
55
                           @DefaultValue("") @QueryParam("sortby") String orderby,
56
                           @DefaultValue("true") @QueryParam("descending") boolean descending,
57
                           @DefaultValue("") @QueryParam("types") String types,
58
                                     @QueryParam("token") String token,
59
                           @Context HttpServletRequest request) {
60

    
61
        if(!JWTValidator.isValid(token)) {
62
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
63
                    .type(MediaType.APPLICATION_JSON)
64
                    .build();
65
        }
66

    
67
        if(Authorization.isAdmin(token)) {
68

    
69
            int total = -1;
70

    
71
            if (projectId == null || projectId.isEmpty()) {
72
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
73
                        .type(MediaType.APPLICATION_JSON).build();
74
            }
75

    
76
            List<Claim> claims = null;
77
            List<String> listTypes = new ArrayList<String>();
78
            String[] types_array = types.split(",");
79
            for (int i = 0; i < types_array.length; i++) {
80
                if (types_array[i].length() > 0) {
81
                    listTypes.add(types_array[i]);
82
                }
83
            }
84
            try {
85
                claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, listTypes);
86
                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, listTypes);
87

    
88
            } catch (Exception e) {
89
                logger.error("Could not fetch claims for project with id " + projectId, e);
90
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
91
                        " for projects with id " + projectId + ".", e)).type(MediaType.APPLICATION_JSON).build();
92
            }
93

    
94
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
95
        }
96

    
97
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
98
                .type(MediaType.APPLICATION_JSON)
99
                .build();
100
    }
101

    
102

    
103
    @GET
104
    @Path("/contexts/{contextId}/claims")
105
    @Produces(MediaType.APPLICATION_JSON)
106
    public Response getContextClaims(@PathParam("contextId") String contextId,
107
                           @DefaultValue("0") @QueryParam("offset") int offset,
108
                           @DefaultValue("20") @QueryParam("limit") int limit,
109
                           @DefaultValue("") @QueryParam("keyword") String keyword,
110
                           @DefaultValue("") @QueryParam("sortby") String orderby,
111
                           @DefaultValue("true") @QueryParam("descending") boolean descending,
112
                           @DefaultValue("") @QueryParam("types") String types,
113
                                     @QueryParam("token") String token,
114
                                     @Context HttpServletRequest request) {
115

    
116
        if(!JWTValidator.isValid(token)) {
117
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
118
                    .type(MediaType.APPLICATION_JSON)
119
                    .build();
120
        }
121

    
122
        if(Authorization.isAdmin(token)) {
123

    
124
            int total = -1;
125
            if (contextId == null || contextId.isEmpty()) {
126
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
127
                        .type(MediaType.APPLICATION_JSON).build();
128
            }
129

    
130
            List<Claim> claims = null;
131
            List<String> listTypes = new ArrayList<String>();
132
            String[] types_array = types.split(",");
133
            for (int i = 0; i < types_array.length; i++) {
134
                if (types_array[i].length() > 0) {
135
                    listTypes.add(types_array[i]);
136
                }
137
            }
138
            try {
139
                claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset, keyword, orderby, descending, listTypes);
140
                total = fetchClaimHandler.countClaimsByContext(contextId, keyword, listTypes);
141

    
142
            } catch (Exception e) {
143
                logger.error("Could not fetch claims for context with id " + contextId, e);
144
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
145
                        " for context with id " + contextId + ".", e)).type(MediaType.APPLICATION_JSON).build();
146
            }
147

    
148
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
149
        }
150

    
151
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
152
                .type(MediaType.APPLICATION_JSON)
153
                .build();
154
    }
155

    
156

    
157
    @GET
158
    @Path("/results/{resultId}/claims")
159
    @Produces(MediaType.APPLICATION_JSON)
160
    public Response getResultClaims(@PathParam("resultId") String resultId,
161
                                    @DefaultValue("0") @QueryParam("offset") int offset,
162
                                    @DefaultValue("20") @QueryParam("limit") int limit,
163
                                    @DefaultValue("") @QueryParam("keyword") String keyword,
164
                                    @DefaultValue("") @QueryParam("sortby") String orderby,
165
                                    @DefaultValue("true") @QueryParam("descending") boolean descending,
166
                                    @DefaultValue("") @QueryParam("types") String types,
167
                                    @QueryParam("token") String token,
168
                                    @Context HttpServletRequest request) {
169

    
170
        if(!JWTValidator.isValid(token)) {
171
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
172
                    .type(MediaType.APPLICATION_JSON)
173
                    .build();
174
        }
175

    
176
        if(Authorization.isAdmin(token)) {
177

    
178
            int total = -1;
179
            if (resultId == null || resultId.isEmpty()) {
180
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
181
                        .type(MediaType.APPLICATION_JSON).build();
182
            }
183

    
184
            List<Claim> claims = null;
185
            List<String> listTypes = new ArrayList<String>();
186
            String[] types_array = types.split(",");
187
            for (int i = 0; i < types_array.length; i++) {
188
                if (types_array[i].length() > 0) {
189
                    listTypes.add(types_array[i]);
190
                }
191
            }
192

    
193
            try {
194
                claims = fetchClaimHandler.fetchClaimsByResult(resultId, limit, offset, keyword, orderby, descending, listTypes);
195
                total = fetchClaimHandler.countClaimsByResult(resultId, keyword, listTypes);
196

    
197
            } catch (Exception e) {
198
                logger.error("Could not fetch claims for result with id " + resultId, e);
199
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
200
                        " for result with id " + resultId + ".", e)).type(MediaType.APPLICATION_JSON).build();
201
            }
202

    
203
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
204
        }
205

    
206
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
207
                .type(MediaType.APPLICATION_JSON)
208
                .build();
209
    }
210

    
211

    
212
    @GET
213
    @Path("/users/{userMail}/claims")
214
    @Produces(MediaType.APPLICATION_JSON)
215
    public Response getUserClaims(@PathParam("userMail") String userMail,
216
                                  @DefaultValue("0") @QueryParam("offset") int offset,
217
                                  @DefaultValue("20") @QueryParam("limit") int limit,
218
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
219
                                  @DefaultValue("") @QueryParam("sortby") String orderby,
220
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
221
                                  @DefaultValue("") @QueryParam("types") String types,
222
                                  @QueryParam("token") String token,
223
                                  @Context HttpServletRequest request) {
224

    
225

    
226
        if(!JWTValidator.isValid(token)) {
227
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
228
                    .type(MediaType.APPLICATION_JSON)
229
                    .build();
230
        }
231

    
232
        if(Authorization.isRegistered(token)) {
233

    
234
            int total = -1;
235
            EmailValidator emailValidator = EmailValidator.getInstance();
236

    
237
            if (userMail == null || userMail.isEmpty()) {
238
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
239
                        .type(MediaType.APPLICATION_JSON).build();
240
            }
241

    
242
            if (!emailValidator.isValid(userMail)) {
243
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
244
                        .type(MediaType.APPLICATION_JSON).build();
245
            }
246

    
247
            List<Claim> claims = null;
248
            List<String> listTypes = new ArrayList<String>();
249
            String[] types_array = types.split(",");
250
            for (int i = 0; i < types_array.length; i++) {
251
                if (types_array[i].length() > 0) {
252
                    listTypes.add(types_array[i]);
253
                }
254
            }
255
            try {
256
                claims = fetchClaimHandler.fetchClaimsByUser(userMail, limit, offset, keyword, orderby, descending, listTypes);
257
                total = fetchClaimHandler.countClaimsByUser(userMail, keyword, listTypes);
258

    
259
            } catch (Exception e) {
260
                logger.error("Could not fetch claims for result with id " + userMail, e);
261
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
262
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
263
            }
264

    
265
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
266
        }
267
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
268
                .type(MediaType.APPLICATION_JSON)
269
                .build();
270
    }
271

    
272

    
273
    @GET
274
    @Path("/claims/{claimId}")
275
    @Produces(MediaType.APPLICATION_JSON)
276
    public Response getClaimsById(@PathParam("claimId") String claimId,
277
                                  @DefaultValue("0") @QueryParam("offset") int offset,
278
                                  @DefaultValue("20") @QueryParam("limit") int limit,
279
                                  @QueryParam("token") String token,
280
                                  @Context HttpServletRequest request) {
281

    
282
        List<Claim> claims = null;
283

    
284
        int total = -1;
285
        if (claimId == null || claimId.isEmpty()) {
286
            try {
287
                claims = fetchClaimHandler.fetchAllClaims(limit, offset);
288
                total = fetchClaimHandler.countAllClaims("", new ArrayList<String>());
289

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

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

    
299
        try {
300
            Claim claim = fetchClaimHandler.fetchClaimById(claimId);
301
            if (claim == null) {
302
                return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Cannot find claim with id " + claimId + "."))
303
                        .type(MediaType.APPLICATION_JSON).build();
304
            }
305

    
306
            return Response.status(200).entity(composeDataResponse(request, claim, total, offset, limit)).build();
307

    
308
        } catch (Exception e) {
309
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claim " +
310
                    "with id " + claimId + " id.", e)).type(MediaType.APPLICATION_JSON).build();
311
        }
312
        
313
    }
314

    
315
    @GET
316
    @Path("/claims")
317
    @Produces(MediaType.APPLICATION_JSON)
318
    public Response getAllClaims(@DefaultValue("0") @QueryParam("offset") int offset,
319
                                  @DefaultValue("20") @QueryParam("limit") int limit,
320
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
321
                                  @DefaultValue("date") @QueryParam("sortby") String orderby,
322
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
323
                                  @DefaultValue("") @QueryParam("types") String types,
324
                                  @QueryParam("token") String token,
325
                                  @Context HttpServletRequest request) {
326

    
327
        if(!JWTValidator.isValid(token)) {
328
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
329
                    .type(MediaType.APPLICATION_JSON)
330
                    .build();
331
        }
332

    
333
        if(Authorization.isAdmin(token)) {
334

    
335
            List<Claim> claims = null;
336
            List<String> listTypes = new ArrayList<String>();
337
            String[] types_array = types.split(",");
338
            for (int i = 0; i < types_array.length; i++) {
339
                if (types_array[i].length() > 0) {
340
                    listTypes.add(types_array[i]);
341
                }
342
            }
343
            logger.debug("Types: " + listTypes.toString());
344

    
345
            int total = -1;
346
            try {
347
                claims = fetchClaimHandler.fetchAllClaims(limit, offset, keyword, orderby, descending, listTypes);
348
                total = fetchClaimHandler.countAllClaims(keyword, listTypes);
349

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

    
352
            } catch (Exception e) {
353
                logger.error("Could not fetch claims.", e);
354
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
355
                        .type(MediaType.APPLICATION_JSON).build();
356
            }
357
        }
358

    
359
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
360
               .type(MediaType.APPLICATION_JSON)
361
               .build();
362
    }
363

    
364

    
365
    @POST
366
    @Path("/claims/{claimId}")
367
    @Produces(MediaType.APPLICATION_JSON)
368
    public Response deleteClaim(@PathParam("claimId") String claimId,
369
                                @QueryParam("token") String token) {
370

    
371
        if (Authorization.isRegistered(token)) {
372
            if (claimId == null || claimId.isEmpty()) {
373
                return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
374
                        .type(MediaType.APPLICATION_JSON).build();
375
            }
376

    
377
            try {
378
                if (claimHandler.deleteClaim(claimId)) {
379
                    return Response.status(204).entity(compose204Message()).type(MediaType.APPLICATION_JSON).build();
380
                }
381

    
382
            } catch (Exception e) {
383
                logger.error("Fail to delete claim with id " + claimId + ".", e);
384
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId + ".", e))
385
                        .type(MediaType.APPLICATION_JSON).build();
386
            }
387

    
388
            return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
389
                    .type(MediaType.APPLICATION_JSON).build();
390
        }
391

    
392
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
393
                .type(MediaType.APPLICATION_JSON)
394
                .build();
395
    }
396
/*
397

    
398
    @DELETE
399
    @Path("/claims/{claimId}")
400
    public Response deleteClaim(@PathParam("claimId") String claimId) {
401

    
402
        if (claimId == null || claimId.isEmpty()) {
403
            return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
404
                    .header("Access-Control-Allow-Methods", "DELETE")
405
                    .type(MediaType.APPLICATION_JSON).build();
406
        }
407

    
408
        try {
409
            if(claimHandler.deleteClaim(claimId)) {
410
                return Response.status(204).entity(compose204Message()).header("Access-Control-Allow-Origin", "*")
411
                        .header("Access-Control-Allow-Methods", "DELETE").type(MediaType.APPLICATION_JSON).build();
412
            }
413

    
414
        } catch (Exception e) {return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
415
                    .type(MediaType.APPLICATION_JSON)
416
                    .build();
417
            logger.error("Fail to delete claim with id " + claimId + ".", e);
418
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId +".", e))
419
                    .header("Access-Control-Allow-Origin", "*")
420
                    .header("Access-Control-Allow-Methods", "DELETE")
421
                    .type(MediaType.APPLICATION_JSON).build();
422
        }
423

    
424
        return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
425
                .header("Access-Control-Allow-Methods", "DELETE")
426
                .type(MediaType.APPLICATION_JSON).build();
427
    }
428
 */
429
@DELETE
430
@Path("/claims/bulk")
431
@Produces(MediaType.APPLICATION_JSON)
432
public Response deleteBulkClaims(@QueryParam("claimId") List<String> claimIds,
433
                                 @QueryParam("token") String token) {
434
    ArrayList<String> deletedIds= new ArrayList<String>();
435
    ArrayList<String> notFoundIds= new ArrayList<String>();
436
    logger.debug("Trying to delete claims with ids: " + claimIds.toString() + ".");
437
    if (claimIds == null || claimIds.size() == 0) {
438
        return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
439
                .type(MediaType.APPLICATION_JSON).build();
440
    }
441

    
442
    for (String claimId : claimIds) {
443
        try {
444
            if (claimHandler.deleteClaim(claimId)) {
445
                deletedIds.add(claimId);
446
            } else {
447
                notFoundIds.add(claimId);
448
            }
449

    
450
        } catch (Exception e) {
451
            logger.error("Fail to delete claim with id " + claimId + ".", e);
452
            notFoundIds.add(claimId);
453
        }
454
    }
455
    logger.debug("Successfully deleted " + deletedIds.size() + " from " + claimIds.size()  +". Deleted claims with ids: " + deletedIds.toString() + ".");
456
    if (claimIds.size() == notFoundIds.size()) {
457
        return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
458
                .type(MediaType.APPLICATION_JSON).build();
459
    } else if (claimIds.size() == notFoundIds.size()) {
460
        return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
461
    } else {
462
        return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
463
    }
464

    
465

    
466
}
467

    
468
    @POST
469
    @Path("/claims")
470
    @Produces(MediaType.APPLICATION_JSON)
471
    @Consumes(MediaType.APPLICATION_JSON)
472
    public Response addClaim(String input, @Context HttpServletRequest request,
473
                             @QueryParam("token") String token) {
474

    
475
        JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
476

    
477
        String claimedBy = jsonObject.get("claimedBy").getAsString();
478
        logger.info("claimedBy " + claimedBy);
479

    
480
        String sourceId = jsonObject.get("sourceId").getAsString();
481
        logger.info("sourceId " + sourceId);
482
        String sourceType = jsonObject.get("sourceType").getAsString();
483
        logger.info("sourceType " + sourceType);
484
        String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
485
        logger.info("sourceCollectedFrom " + sourceCollectedFrom);
486
        String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
487
        logger.info("sourceAccessRights " + sourceAccessRights);
488
        String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
489
        sourceEmbargoEndDate= (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals(""))?null: sourceEmbargoEndDate;
490
        logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
491

    
492
        String targetId = jsonObject.get("targetId").getAsString();
493
        logger.info("targetId " + targetId);
494
        String targetType = jsonObject.get("targetType").getAsString();
495
        logger.info("targetType " + targetType);
496
        String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
497
        logger.info("targetCollectedFrom " + targetCollectedFrom);
498
        String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
499
        logger.info("targetAccessRights " + targetAccessRights);
500
        String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
501
        targetEmbargoEndDate= (targetEmbargoEndDate != null && targetEmbargoEndDate.equals(""))?null: targetEmbargoEndDate;
502
        logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
503

    
504
        EmailValidator emailValidator = EmailValidator.getInstance();
505
        if (!emailValidator.isValid(claimedBy)) {
506
            return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
507
                    .type(MediaType.APPLICATION_JSON).build();
508
        }
509

    
510

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

    
515
        } catch (ClaimValidationException ve) {
516
            return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
517
                    .type(MediaType.APPLICATION_JSON).build();
518

    
519
        } catch (Exception e) {
520
            logger.error("Fail to add new claim.", e);
521
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
522
                    .type(MediaType.APPLICATION_JSON).build();
523
        }
524

    
525
    }
526

    
527
    @POST
528
    @Path("/claims/bulk")
529
    @Produces(MediaType.APPLICATION_JSON)
530
    @Consumes(MediaType.APPLICATION_JSON)
531
    public Response addBulkClaims(String input, @Context HttpServletRequest request,
532
                                  @QueryParam("token") String token) {
533
        ArrayList<String> insertedIds= new ArrayList<String>();
534
        JsonArray errorInClaims= new JsonArray();
535
        int code200 = 0; int code400 = 0; int code500 = 0;
536
        JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
537
        for (JsonElement je: jsonArray) {
538
            JsonObject jsonObject = je.getAsJsonObject();
539

    
540
            logger.info("targetId " + jsonObject.toString());
541
            String claimedBy = jsonObject.get("claimedBy").getAsString();
542
            logger.info("claimedBy " + claimedBy);
543

    
544
            String sourceId = jsonObject.get("sourceId").getAsString();
545
            logger.info("sourceId " + sourceId);
546
            String sourceType = jsonObject.get("sourceType").getAsString();
547
            logger.info("sourceType " + sourceType);
548
            String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
549
            logger.info("sourceCollectedFrom " + sourceCollectedFrom);
550
            String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
551
            logger.info("sourceAccessRights " + sourceAccessRights);
552
            String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
553
            sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
554
            logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
555

    
556
            String targetId = jsonObject.get("targetId").getAsString();
557
            logger.info("targetId " + targetId);
558
            String targetType = jsonObject.get("targetType").getAsString();
559
            logger.info("targetType " + targetType);
560
            String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
561
            logger.info("targetCollectedFrom " + targetCollectedFrom);
562
            String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
563
            logger.info("targetAccessRights " + targetAccessRights);
564
            String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
565
            targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
566
            logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
567

    
568
            EmailValidator emailValidator = EmailValidator.getInstance();
569
            if (!emailValidator.isValid(claimedBy)) {
570
                jsonObject.addProperty("error","user");
571
//                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
572
//                        .type(MediaType.APPLICATION_JSON).build();
573
                code400++;
574
                errorInClaims.add(jsonObject);
575
            }
576

    
577

    
578
            try {
579
                String claimId = claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate);
580
                insertedIds.add(claimId);
581
                code200++;
582
//                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
583

    
584
            } catch (ClaimValidationException ve) {
585
//                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
586
//                        .type(MediaType.APPLICATION_JSON).build();
587
                jsonObject.addProperty("error","validation");
588
                errorInClaims.add(jsonObject);
589
                code400++;
590

    
591
            } catch (Exception e) {
592
//                logger.error("Fail to add new claim.", e);
593
//                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
594
//                        .type(MediaType.APPLICATION_JSON).build();
595
                jsonObject.addProperty("error","insertion");
596
                errorInClaims.add(jsonObject);
597
                code500++;
598
            }
599
        }
600
        if (jsonArray.size() == code500) {
601
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
602
                    .type(MediaType.APPLICATION_JSON).build();
603
        } else if (code200 > 0) {
604
            return Response.status(200).entity(compose201BulkInsertMessage(request, insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
605
        } else {
606
            return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
607
                    .type(MediaType.APPLICATION_JSON).build();
608
        }
609

    
610

    
611

    
612

    
613
    }
614

    
615
    @Path("/communities")
616
    @GET
617
    @Produces(MediaType.APPLICATION_JSON)
618
    public Response fetchCommunities(@QueryParam("token") String token) throws ISLookUpServiceException {
619
        //it needs to have at lease one category with @claim=true
620
        List<String> communities = lookupServiceLocator.getService().quickSearchProfile
621
                ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')  \n" +
622
                        "                where $x//context[@type='community']//category[@claim='true'] \n" +
623
                        "            return <communities>{$x//context/@id}{$x//context/@label}</communities>");
624

    
625
        return Response.status(200).entity(composeDataResponse(xml2Json(communities))).type(MediaType.APPLICATION_JSON).build();
626

    
627
    }
628

    
629
    @Path("/communities/{communityid}/categories")
630
    @GET
631
    @Produces(MediaType.APPLICATION_JSON)
632
    public Response fetchCommunityCategories(@PathParam("communityid") String communityid,
633
                                             @QueryParam("token") String token) throws ISLookUpServiceException {
634
        List<String> categories = lookupServiceLocator.getService().quickSearchProfile
635
                ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')//context[@id='" + communityid + "']//category[@claim=\'true\']\n" +
636
                        "return <category>{$x/@id}{$x/@label}</category>");
637

    
638
        logger.info("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')//context[@id='" + communityid + "']//category[@claim=\'true\']\n" +
639
                "return <category>{$x/@id}{$x/@label}</category>");
640
        
641
        if(categories==null || categories.isEmpty()) {
642
            return Response.status(404).entity(compose404Message("There are no categories for community with id " + communityid)).type(MediaType.APPLICATION_JSON).build();
643
        }
644

    
645

    
646
        xml2Json(categories);
647

    
648
        return Response.status(200).entity(composeDataResponse(xml2Json(categories))).type(MediaType.APPLICATION_JSON).build();
649

    
650
    }
651

    
652
    @Path("/categories/{categoryid}/concepts")
653
    @GET
654
    @Produces(MediaType.APPLICATION_JSON)
655
    public Response fetchCategoryConcepts(@PathParam("categoryid") String categoryid,
656
                                          @QueryParam("token") String token) throws ISLookUpServiceException {
657
        List<String> concepts = lookupServiceLocator.getService().quickSearchProfile
658
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType') return $x//category[@id='"+ categoryid +"']//concept");
659

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

    
664
        return Response.status(200).entity(composeDataResponse(xml2Json(concepts))).type(MediaType.APPLICATION_JSON).build();
665

    
666
    }
667

    
668
    private String xml2Json(List<String> input) {
669
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
670
        StringBuilder builder = new StringBuilder();
671
        for(String category: input) {
672
            builder.append(category);
673
        }
674

    
675
        return builder.toString();
676
    }
677

    
678
    private String compose400Message(String message) {
679
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
680
    }
681

    
682
    private String compose400Message(String message, Exception exception) {
683
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
684
                "\"description\" : \""+  exception.getMessage() +"\" }";
685
    }
686

    
687
    private String compose403Message(String message) {
688
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
689
                "\"description\" : \" }";
690
    }
691

    
692
    private String compose404BulkDeleteMessage(String message, ArrayList<String> deletedIds, ArrayList<String> notFoundIds) {
693
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \""+  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
694
    }
695
    private String compose404Message(String message) {
696
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
697
    }
698

    
699
    private String compose400BulkInsertMessage(String message, ArrayList<String> insertdIds,JsonArray errorInClaims) {
700
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \""+  ", \"insertdIds\" : " + new Gson().toJson(insertdIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
701
    }
702

    
703
    private String compose500Message(String message, Exception exception) {
704
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
705
                "\"description\" : \""+  exception.getMessage() +"\" }";
706
    }
707

    
708
    private String compose500BulkInsertMessage(String message,  ArrayList<String> insertdIds, JsonArray errorInClaims) {
709
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
710
                "\"description\" : \""+   "\" , " +  "\"insertdIds\" : " + new Gson().toJson(insertdIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
711
    }
712
    private String compose500BulkDeleteMessage(String message,  ArrayList<String> deletedIds, ArrayList<String> notFoundIds, Exception exception) {
713
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
714
                "\"description\" : \""+  exception.getMessage() +"\" ," +  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
715
    }
716
    private  String compose200Message(){
717
        return " { \"status\" : \"success\", \"code\": \"200\" }";
718
    }
719

    
720
    private  String compose204Message(){
721
        return " { \"status\" : \"success\", \"code\": \"204\" }";
722
    }
723
    private  String compose204BulkDeleteMessage(ArrayList<String> deletedIds, ArrayList<String> notFoundIds){
724
        return " { \"status\" : \"success\", \"code\": \"204\", "+ "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + "}";
725
    }
726

    
727

    
728
    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
729
        String url = request.getRequestURL().toString();
730
        //String query = request.getQueryString();
731

    
732
        return " { \"status\" : \"success\", \"code\": \"201\", \"link\": \"" + url  +"/"+ claimId +"\" }";
733
    }
734
    private  String compose201BulkInsertMessage(@Context HttpServletRequest request, ArrayList<String> insertedIds, JsonArray errorInClaims){
735
        String url = request.getRequestURL().toString();
736
        //String query = request.getQueryString();
737

    
738
        return " { \"status\" : \"success\", \"code\": \"201\","+ "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims)+ "}";
739
    }
740
    private String composeDataResponse(HttpServletRequest request, List<Claim> claims, int total, int offset, int limit) {
741
        return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", " + composePaging(request, total, offset, limit) + ", "
742
                + "\"data\" : " + new Gson().toJson(claims) + " }";
743
    }
744

    
745
    private String composeDataResponse(String xml) {
746
        return " { \"status\" : \"success\", \"code\": \"200\", "
747
                + "\"data\" : " + XML.toJSONObject(xml).toString() + " }";
748
    }
749

    
750
    private String composeDataResponse(HttpServletRequest request, Claim claim, int total, int offset, int limit) {
751
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(claim) + " }";
752
    }
753

    
754
    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
755
        logger.info("total " + total);
756
        logger.info("currentOffset " + currentOffset);
757
        logger.info("limit " + limit);
758

    
759
        String url = request.getRequestURL().toString();
760
        //String query = request.getQueryString();
761

    
762
        String first = url+"?offset=0&limit=20";
763

    
764
        int previousPage;
765
        int nextPage;
766
        int lastPage;
767

    
768
        if (total <= limit) {
769
            lastPage = 0;
770
        } else {
771
            if(total%limit == 0) {
772
                lastPage = total/limit-1;
773
            } else {
774
                lastPage = total/limit ;
775
            }
776
        }
777
        String last = url+"?offset=" + lastPage + "&limit=20";
778

    
779
        if (currentOffset-1 <= 0) {
780
            previousPage = 0;
781
        } else {
782
            previousPage = currentOffset-1;
783
        }
784
        String previous = url+"?offset=" + previousPage + "&limit=20";
785

    
786
        if (currentOffset+1 >= lastPage) {
787
            nextPage = lastPage;
788

    
789
        } else {
790
            nextPage = currentOffset + 1;
791
        }
792
        String next = url+"?offset=" + nextPage + "&limit=20";
793

    
794
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + first +"\"}, {\"rel\":\"last\", \"href\":\"" + last + "\"}, {\"rel\":\"previous\", \"href\": \"" + previous + "\"}, {\"rel\":\"next\", \"href\":\"" +  next +"\"}"+ "]";
795
    }
796
    private String composeTotalResults(int total) {
797
        return "\"total\": \""+total+"\"";
798
    }
799

    
800
    private String composePaging2( int total, int currentOffset, int limit) {
801
       // String url = request.getRequestURL().toString();
802
        //String query = request.getQueryString();
803

    
804
        //String first = url+"?offset=0&limit=20";
805

    
806
        int previousPage;
807
        int nextPage;
808
        int lastPage;
809

    
810
        if (total < currentOffset) {
811
            lastPage = 0;
812
        } else {
813
            if(total%limit == 0) {
814
                lastPage = total/limit-1;
815
            } else {
816
                lastPage = total/limit ;
817
            }
818
        }
819
        //String last = url+"?offset=" + lastPage + "&limit=20";
820

    
821
        if (currentOffset-1 <= 0) {
822
            previousPage = 0;
823
        } else {
824
            previousPage = currentOffset-1;
825
        }
826
        //String previous = url+"?offset=" + previousPage + "&limit=20";
827

    
828
        if (currentOffset+1 >= lastPage) {
829
            nextPage = lastPage;
830

    
831
        } else {
832
            nextPage = currentOffset + 1;
833
        }
834
        //String next = url+"?offset=" + nextPage + "&limit=20";
835

    
836
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + 0 +"\"}, {\"rel\":\"last\", \"href\":\"" + lastPage + "\"}, {\"rel\":\"previous\", \"href\": \"" + previousPage + "\"}, {\"rel\":\"next\", \"href\":\"" +  nextPage +"\"}"+ "]";
837
    }
838

    
839
     public static void main(String[] args) {
840
        HelloWorldService helloWorldService = new HelloWorldService();
841

    
842

    
843
/*        System.out.println(helloWorldService.composePaging2(100, 0, 20));
844
        System.out.println(helloWorldService.composePaging2(100, 4, 20));
845

    
846
        System.out.println(helloWorldService.composePaging2(99, 4, 20));
847
        System.out.println(helloWorldService.composePaging2(99, 4, 20));
848

    
849
        System.out.println(helloWorldService.composePaging2(85, 4, 20));
850

    
851
         System.out.println(helloWorldService.composePaging2(0, 4, 20));
852
*/
853
/*
854
         EmailValidator emailValidator = EmailValidator.getInstance();
855
         System.out.println(emailValidator.isValid("jate@gdddd"));
856

    
857
         InternetAddress emailAddr = null;
858
         try {
859
             emailAddr = new InternetAddress("jate@gdddd");
860
             emailAddr.validate();
861
         } catch (AddressException e) {
862
             System.out.println("false");
863
         }
864
         System.out.println("true");
865
*/
866
         ArrayList<String> insertedIds= new ArrayList<String>();
867
         insertedIds.add("1");
868
         insertedIds.add("2");
869
         insertedIds.add("3");
870
//         System.out.println(helloWorldService.compose204BulkInsertMessage(insertedIds,insertedIds));
871

    
872
    }
873

    
874

    
875
}
    (1-1/1)