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 eu.dnetlib.openaire.rest.authorization.Authorization;
14
import eu.dnetlib.openaire.rest.inputHandler.UserHandler;
15
import eu.dnetlib.openaire.rest.security.JWTValidator;
16
import gr.uoa.di.driver.util.ServiceLocator;
17
import org.apache.commons.validator.EmailValidator;
18
import org.apache.log4j.Logger;
19
import org.json.XML;
20
import org.springframework.beans.factory.annotation.Autowired;
21
import org.springframework.stereotype.Component;
22

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

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

    
39
    private static final Logger logger = Logger.getLogger(HelloWorldService.class);
40

    
41
    @Autowired
42
    private FetchClaimHandler fetchClaimHandler = null;
43

    
44
    @Autowired
45
    private FetchProjectHandler fetchProjectHandler= null;
46

    
47
    @Resource
48
    private ServiceLocator<ISLookUpService> lookupServiceLocator = null;
49

    
50
    @Autowired
51
    private ClaimHandler claimHandler = null;
52

    
53
    @Autowired
54
    private DirectIndexHandler directIndexHandler = null;
55

    
56

    
57

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

    
71
        if(!JWTValidator.isValid(token)) {
72
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
73
                    .type(MediaType.APPLICATION_JSON)
74
                    .build();
75
        }
76
        if(Authorization.isAdmin(token)) {
77

    
78
            int total = -1;
79

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

    
85
            List<Claim> claims = null;
86
            List<String> listTypes = new ArrayList<String>();
87
            String[] types_array = types.split(",");
88
            for (int i = 0; i < types_array.length; i++) {
89
                if (types_array[i].length() > 0) {
90
                    listTypes.add(types_array[i]);
91
                }
92
            }
93
            try {
94
                claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, listTypes,false);
95
                total = fetchClaimHandler.countClaimsByProject(projectId, keyword, listTypes);
96

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

    
102
            }
103

    
104
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
105
        }
106

    
107
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
108
                .type(MediaType.APPLICATION_JSON)
109
                .build();
110
    }
111

    
112
    @GET
113
    @Path("project/claims")
114
    @Produces(MediaType.APPLICATION_JSON)
115
    public Response getProjectClaimsByToken(@QueryParam("projectToken") String projectToken,
116
                                     @DefaultValue("0") @QueryParam("offset") int offset,
117
                                     @DefaultValue("20") @QueryParam("limit") int limit,
118
                                     @DefaultValue("") @QueryParam("keyword") String keyword,
119
                                     @DefaultValue("") @QueryParam("sortby") String orderby,
120
                                     @DefaultValue("true") @QueryParam("descending") boolean descending,
121
                                     @DefaultValue("") @QueryParam("types") String types,
122
                                     @QueryParam("token") String token,
123
                                     @Context HttpServletRequest request) {
124

    
125
        if(!JWTValidator.isValid(token)) {
126
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
127
                    .type(MediaType.APPLICATION_JSON)
128
                    .build();
129
        }
130
        if(Authorization.isRegistered(token)) {
131
            String userMail = UserHandler.getMail(token);
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
            List<String> listTypes = new ArrayList<String>();
142
            String[] types_array = types.split(",");
143
            for (int i = 0; i < types_array.length; i++) {
144
                if (types_array[i].length() > 0) {
145
                    listTypes.add(types_array[i]);
146
                }
147
            }
148
            try {
149
                String projectId = fetchProjectHandler.fetchProjectIdByToken(projectToken,userMail);
150
                if(projectId == null){
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
                }else{
155
                    claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset, keyword, orderby, descending, listTypes,true);
156
                    total = fetchClaimHandler.countClaimsByProject(projectId, keyword, listTypes);
157
                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
158
                }
159

    
160
            } catch (SQLStoreException|Exception e) {
161
                logger.error("Could not fetch claims for project token " + projectToken, e);
162
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
163
                        " for projects with token " + projectToken + ".", e)).type(MediaType.APPLICATION_JSON).build();
164
            }
165
        }
166

    
167
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
168
                .type(MediaType.APPLICATION_JSON)
169
                .build();
170
    }
171
    @GET
172
    @Path("/contexts/{contextId}/claims")
173
    @Produces(MediaType.APPLICATION_JSON)
174
    public Response getContextClaims(@PathParam("contextId") String contextId,
175
                           @DefaultValue("0") @QueryParam("offset") int offset,
176
                           @DefaultValue("20") @QueryParam("limit") int limit,
177
                           @DefaultValue("") @QueryParam("keyword") String keyword,
178
                           @DefaultValue("") @QueryParam("sortby") String orderby,
179
                           @DefaultValue("true") @QueryParam("descending") boolean descending,
180
                           @DefaultValue("") @QueryParam("types") String types,
181
                                     @QueryParam("token") String token,
182
                                     @Context HttpServletRequest request) {
183

    
184
        logger.debug("Calling API for context with token " + token);
185

    
186
        if(!JWTValidator.isValid(token)) {
187
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
188
                    .type(MediaType.APPLICATION_JSON)
189
                    .build();
190
        }
191

    
192
        if(Authorization.isAdmin(token)) {
193

    
194
            int total = -1;
195
            if (contextId == null || contextId.isEmpty()) {
196
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
197
                        .type(MediaType.APPLICATION_JSON).build();
198
            }
199

    
200
            List<Claim> claims = null;
201
            List<String> listTypes = new ArrayList<String>();
202
            String[] types_array = types.split(",");
203
            for (int i = 0; i < types_array.length; i++) {
204
                if (types_array[i].length() > 0) {
205
                    listTypes.add(types_array[i]);
206
                }
207
            }
208
            try {
209
                claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset, keyword, orderby, descending, listTypes,false);
210
                total = fetchClaimHandler.countClaimsByContext(contextId, keyword, listTypes);
211

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

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

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

    
226

    
227
    @GET
228
    @Path("/results/{resultId}/claims")
229
    @Produces(MediaType.APPLICATION_JSON)
230
    public Response getResultClaims(@PathParam("resultId") String resultId,
231
                                    @DefaultValue("0") @QueryParam("offset") int offset,
232
                                    @DefaultValue("20") @QueryParam("limit") int limit,
233
                                    @DefaultValue("") @QueryParam("keyword") String keyword,
234
                                    @DefaultValue("") @QueryParam("sortby") String orderby,
235
                                    @DefaultValue("true") @QueryParam("descending") boolean descending,
236
                                    @DefaultValue("") @QueryParam("types") String types,
237
                                    @QueryParam("token") String token,
238
                                    @Context HttpServletRequest request) {
239

    
240
        if(!JWTValidator.isValid(token)) {
241
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
242
                    .type(MediaType.APPLICATION_JSON)
243
                    .build();
244
        }
245
        if(Authorization.isAdmin(token)) {
246

    
247
            int total = -1;
248
            if (resultId == null || resultId.isEmpty()) {
249
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
250
                        .type(MediaType.APPLICATION_JSON).build();
251
            }
252

    
253
            List<Claim> claims = null;
254
            List<String> listTypes = new ArrayList<String>();
255
            String[] types_array = types.split(",");
256
            for (int i = 0; i < types_array.length; i++) {
257
                if (types_array[i].length() > 0) {
258
                    listTypes.add(types_array[i]);
259
                }
260
            }
261

    
262
            try {
263
                claims = fetchClaimHandler.fetchClaimsByResult(resultId, limit, offset, keyword, orderby, descending, listTypes,false);
264
                total = fetchClaimHandler.countClaimsByResult(resultId, keyword, listTypes);
265

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

    
272
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
273
        }
274

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

    
280

    
281
    @GET
282
    @Path("/users/{userMail}/claims")
283
    @Produces(MediaType.APPLICATION_JSON)
284
    public Response getUserClaims(@PathParam("userMail") String userMail,
285
                                  @DefaultValue("0") @QueryParam("offset") int offset,
286
                                  @DefaultValue("20") @QueryParam("limit") int limit,
287
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
288
                                  @DefaultValue("") @QueryParam("sortby") String orderby,
289
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
290
                                  @DefaultValue("") @QueryParam("types") String types,
291
                                  @QueryParam("token") String token,
292
                                  @Context HttpServletRequest request) {
293

    
294

    
295
        if(!JWTValidator.isValid(token)) {
296
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
297
                    .type(MediaType.APPLICATION_JSON)
298
                    .build();
299
        }
300
        if(Authorization.isRegistered(token)) {
301
//            String userMail = UserHandler.getMail(token);
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
            List<String> listTypes = new ArrayList<String>();
317
            String[] types_array = types.split(",");
318
            for (int i = 0; i < types_array.length; i++) {
319
                if (types_array[i].length() > 0) {
320
                    listTypes.add(types_array[i]);
321
                }
322
            }
323
            try {
324
                claims = fetchClaimHandler.fetchClaimsByUser(userMail, limit, offset, keyword, orderby, descending, listTypes,false);
325
                total = fetchClaimHandler.countClaimsByUser(userMail, keyword, listTypes);
326

    
327
            } catch (SQLStoreException|Exception e) {
328
                logger.error("Could not fetch claims for result with id " + userMail, e);
329
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
330
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
331
            }
332

    
333
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
334
        }
335
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
336
                .type(MediaType.APPLICATION_JSON)
337
                .build();
338
    }
339

    
340
    @GET
341
    @Path("/claims/{claimId}")
342
    @Produces(MediaType.APPLICATION_JSON)
343
    public Response getClaimsById(@PathParam("claimId") String claimId,
344
                                  @DefaultValue("0") @QueryParam("offset") int offset,
345
                                  @DefaultValue("20") @QueryParam("limit") int limit,
346
                                  @QueryParam("token") String token,
347
                                  @Context HttpServletRequest request) {
348

    
349
        if(!JWTValidator.isValid(token)) {
350
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
351
                    .type(MediaType.APPLICATION_JSON)
352
                    .build();
353
        }
354
        if(Authorization.isRegistered(token)) {
355

    
356
            List<Claim> claims = null;
357

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

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

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

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

    
380
                return Response.status(200).entity(composeDataResponse(claim)).build();
381

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

    
392
    @GET
393
    @Path("/claims")
394
    @Produces(MediaType.APPLICATION_JSON)
395
    public Response getAllClaims(@DefaultValue("0") @QueryParam("offset") int offset,
396
                                  @DefaultValue("20") @QueryParam("limit") int limit,
397
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
398
                                  @DefaultValue("date") @QueryParam("sortby") String orderby,
399
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
400
                                  @DefaultValue("") @QueryParam("types") String types,
401
                                  @QueryParam("token") String token,
402
                                  @Context HttpServletRequest request) {
403

    
404
        if(!JWTValidator.isValid(token)) {
405
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
406
                    .type(MediaType.APPLICATION_JSON)
407
                    .build();
408
        }
409
        if(Authorization.isAdmin(token)) {
410

    
411
            List<Claim> claims = null;
412
            List<String> listTypes = new ArrayList<String>();
413
            String[] types_array = types.split(",");
414
            for (int i = 0; i < types_array.length; i++) {
415
                if (types_array[i].length() > 0) {
416
                    listTypes.add(types_array[i]);
417
                }
418
            }
419
            logger.debug("Types: " + listTypes.toString());
420

    
421
            int total = -1;
422
            try {
423
                claims = fetchClaimHandler.fetchAllClaims(limit, offset, keyword, orderby, descending, listTypes,false);
424
                total = fetchClaimHandler.countAllClaims(keyword, listTypes);
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) && (userHandler.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
                                     @QueryParam("token") String token) {
523

    
524
        if(!JWTValidator.isValid(token)) {
525
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
526
                    .type(MediaType.APPLICATION_JSON)
527
                    .build();
528
        }
529

    
530
        ArrayList<String> deletedIds= new ArrayList<String>();
531
        ArrayList<String> notFoundIds= new ArrayList<String>();
532

    
533
        if (claimIds == null || claimIds.size() == 0) {
534
            return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
535
                    .type(MediaType.APPLICATION_JSON).build();
536
        }
537

    
538
        logger.debug("Trying to delete claims with ids: " + claimIds.toString() + ".");
539

    
540
        for (String claimId : claimIds) {
541
            try {
542

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

    
576
    @POST
577
    @Path("/claims")
578
    @Produces(MediaType.APPLICATION_JSON)
579
    @Consumes(MediaType.APPLICATION_JSON)
580
    public Response addClaim(String input, @Context HttpServletRequest request,
581
                             @QueryParam("token") String token) {
582

    
583
        if(!JWTValidator.isValid(token)) {
584
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
585
                    .type(MediaType.APPLICATION_JSON)
586
                    .build();
587
        }
588
        if(Authorization.isRegistered(token)) {
589
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
590

    
591
            String claimedBy = jsonObject.get("claimedBy").getAsString();
592
            logger.info("claimedBy " + claimedBy);
593

    
594
            String sourceId = jsonObject.get("sourceId").getAsString();
595
            logger.info("sourceId " + sourceId);
596
            String sourceType = jsonObject.get("sourceType").getAsString();
597
            logger.info("sourceType " + sourceType);
598
            String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
599
            logger.info("sourceCollectedFrom " + sourceCollectedFrom);
600
            String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
601
            logger.info("sourceAccessRights " + sourceAccessRights);
602
            String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
603
            sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
604
            logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
605

    
606
            String targetId = jsonObject.get("targetId").getAsString();
607
            logger.info("targetId " + targetId);
608
            String targetType = jsonObject.get("targetType").getAsString();
609
            logger.info("targetType " + targetType);
610
            String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
611
            logger.info("targetCollectedFrom " + targetCollectedFrom);
612
            String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
613
            logger.info("targetAccessRights " + targetAccessRights);
614
            String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
615
            targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
616
            logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
617

    
618
            EmailValidator emailValidator = EmailValidator.getInstance();
619
            if (!emailValidator.isValid(claimedBy)) {
620
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
621
                        .type(MediaType.APPLICATION_JSON).build();
622
            }
623

    
624

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

    
629
            } catch (ClaimValidationException ve) {
630
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
631
                        .type(MediaType.APPLICATION_JSON).build();
632

    
633
            } catch (SQLStoreException|Exception e) {
634
                logger.error("Fail to add new claim.", e);
635
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
636
                        .type(MediaType.APPLICATION_JSON).build();
637
            }
638
        }
639
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access."))
640
                .type(MediaType.APPLICATION_JSON)
641
                .build();
642
    }
643

    
644
    @POST
645
    @Path("/claims/bulk")
646
    @Produces(MediaType.APPLICATION_JSON)
647
    @Consumes(MediaType.APPLICATION_JSON)
648
    public Response addBulkClaims(String input, @Context HttpServletRequest request,
649
                                  @QueryParam("token") String token) {
650

    
651
        if(!JWTValidator.isValid(token)) {
652
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
653
                    .type(MediaType.APPLICATION_JSON)
654
                    .build();
655
        }
656
        if (Authorization.isRegistered(token)) {
657
            ArrayList<String> insertedIds = new ArrayList<String>();
658
            JsonArray errorInClaims = new JsonArray();
659

    
660
            int code200 = 0;
661
            int code400 = 0;
662
            int code500 = 0;
663

    
664
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
665
            for (JsonElement je : jsonArray) {
666
                JsonObject jsonObject = je.getAsJsonObject();
667

    
668
                logger.info("targetId " + jsonObject.toString());
669
                String claimedBy = jsonObject.get("claimedBy").getAsString();
670
                logger.info("claimedBy " + claimedBy);
671

    
672
                String sourceId = jsonObject.get("sourceId").getAsString();
673
                logger.info("sourceId " + sourceId);
674
                String sourceType = jsonObject.get("sourceType").getAsString();
675
                logger.info("sourceType " + sourceType);
676
                String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
677
                logger.info("sourceCollectedFrom " + sourceCollectedFrom);
678
                String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
679
                logger.info("sourceAccessRights " + sourceAccessRights);
680
                String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
681
                sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
682
                logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
683

    
684
                String targetId = jsonObject.get("targetId").getAsString();
685
                logger.info("targetId " + targetId);
686
                String targetType = jsonObject.get("targetType").getAsString();
687
                logger.info("targetType " + targetType);
688
                String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
689
                logger.info("targetCollectedFrom " + targetCollectedFrom);
690
                String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
691
                logger.info("targetAccessRights " + targetAccessRights);
692
                String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
693
                targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
694
                logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
695

    
696
                EmailValidator emailValidator = EmailValidator.getInstance();
697
                if (!emailValidator.isValid(claimedBy)) {
698
                    jsonObject.addProperty("error", "user");
699
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
700
                    //                        .type(MediaType.APPLICATION_JSON).build();
701
                    code400++;
702
                    errorInClaims.add(jsonObject);
703
                }
704

    
705

    
706
                try {
707
                    String claimId = claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate);
708
                    insertedIds.add(claimId);
709
                    code200++;
710
                    //                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
711

    
712
                } catch (ClaimValidationException ve) {
713
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
714
                    //                        .type(MediaType.APPLICATION_JSON).build();
715
                    jsonObject.addProperty("error", "validation");
716
                    errorInClaims.add(jsonObject);
717
                    code400++;
718

    
719
                } catch (SQLStoreException|Exception e) {
720
                    //                logger.error("Fail to add new claim.", e);
721
                    //                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
722
                    //                        .type(MediaType.APPLICATION_JSON).build();
723
                    jsonObject.addProperty("error", "insertion");
724
                    errorInClaims.add(jsonObject);
725
                    code500++;
726
                }
727
            }
728
            if (jsonArray.size() == code500) {
729
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
730
                        .type(MediaType.APPLICATION_JSON).build();
731
            } else if (code200 > 0) {
732
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
733
            } else {
734
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
735
                        .type(MediaType.APPLICATION_JSON).build();
736
            }
737
        }
738
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
739
                .type(MediaType.APPLICATION_JSON)
740
                .build();
741

    
742
    }
743
    @POST
744
    @Path("/curate/bulk")
745
    @Produces(MediaType.APPLICATION_JSON)
746
    @Consumes(MediaType.APPLICATION_JSON)
747
    public Response curateBulkClaims(String input, @Context HttpServletRequest request,
748
                                  @QueryParam("token") String token) {
749

    
750
        if(!JWTValidator.isValid(token)) {
751
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
752
                    .type(MediaType.APPLICATION_JSON)
753
                    .build();
754
        }
755
        if (Authorization.isRegistered(token)) {
756
            ArrayList<String> insertedIds = new ArrayList<String>();
757
            JsonArray errorInClaims = new JsonArray();
758
            int code200 = 0;
759
            int code400 = 0;
760
            int code500 = 0;
761
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
762
            String curatedBy = UserHandler.getMail(token);
763

    
764
            for (JsonElement je : jsonArray) {
765
                JsonObject jsonObject = je.getAsJsonObject();
766

    
767
                 String id = jsonObject.get("id").getAsString();
768
                logger.info("id " + id);
769

    
770
                Boolean approved = jsonObject.get("approved").getAsBoolean();
771
                logger.info("approved " + approved);
772
                EmailValidator emailValidator = EmailValidator.getInstance();
773
                if (!emailValidator.isValid(curatedBy)) {
774
                    jsonObject.addProperty("error", "user");
775
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
776
                    //                        .type(MediaType.APPLICATION_JSON).build();
777
                    code400++;
778
                    errorInClaims.add(jsonObject);
779
                }
780

    
781
                try {
782
                    claimHandler.updateClaimCurationInfo(curatedBy,id, approved);
783
                    insertedIds.add(id);
784
                    code200++;
785

    
786
                } catch (SQLStoreException|Exception e) {
787
                    jsonObject.addProperty("error", "insertion");
788
                    errorInClaims.add(jsonObject);
789
                    code500++;
790
                }
791
            }
792
            if (jsonArray.size() == code500) {
793
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to update claims.", insertedIds, errorInClaims))
794
                        .type(MediaType.APPLICATION_JSON).build();
795
            } else if (code200 > 0) {
796
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
797
            } else {
798
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
799
                        .type(MediaType.APPLICATION_JSON).build();
800
            }
801
        }
802
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
803
                .type(MediaType.APPLICATION_JSON)
804
                .build();
805

    
806
    }
807
    @POST
808
    @Path("/feed/bulk")
809
    @Produces(MediaType.APPLICATION_JSON)
810
    @Consumes(MediaType.APPLICATION_JSON)
811
    public Response feedBulkRecords(String input, @Context HttpServletRequest request,@QueryParam("token") String token
812
    ) {
813

    
814
        if(!JWTValidator.isValid(token)) {
815
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
816
                    .type(MediaType.APPLICATION_JSON)
817
                    .build();
818
        }
819
        if (Authorization.isRegistered(token)) {
820
            ArrayList<String> insertedIds = new ArrayList<String>();
821
            JsonArray errorInClaims = new JsonArray();
822
            int code200 = 0;
823
            int code400 = 0;
824
            int code500 = 0;
825
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
826
            for (JsonElement je : jsonArray) {
827
                JsonObject jsonObject = je.getAsJsonObject();
828
                Boolean inserted = directIndexHandler.insertRecord(new Gson().toJson(jsonObject.get("record")));
829
                if (inserted) {
830
                    insertedIds.add(jsonObject.get("id").getAsString());
831
                    code200++;
832
                } else {
833
                    errorInClaims.add(jsonObject.get("id").getAsString());
834
                    code400++;
835
                }
836

    
837

    
838
            }
839
            if (jsonArray.size() == code500) {
840
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
841
                        .type(MediaType.APPLICATION_JSON).build();
842
            } else if (code200 > 0) {
843
                return Response.status(200).entity(compose201BulkInsertMessage(insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
844
            } else {
845
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
846
                        .type(MediaType.APPLICATION_JSON).build();
847
            }
848
        }
849
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
850
                .type(MediaType.APPLICATION_JSON)
851
                .build();
852

    
853
    }
854

    
855
    @Path("/communities")
856
    @GET
857
    @Produces(MediaType.APPLICATION_JSON)
858
    public Response fetchCommunities(@QueryParam("token") String token) throws ISLookUpServiceException {
859

    
860
        if(!JWTValidator.isValid(token)) {
861
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
862
                    .type(MediaType.APPLICATION_JSON)
863
                    .build();
864
        }
865
        if (Authorization.isRegistered(token)) {
866
            //it needs to have at lease one category with @claim=true
867
            List<String> communities = lookupServiceLocator.getService().quickSearchProfile
868
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')  \n" +
869
                            "                where $x//context[@type='community']//category[@claim='true'] \n" +
870
                            "            return <communities>{$x//context/@id}{$x//context/@label}</communities>");
871

    
872
            return Response.status(200).entity(composeDataResponse(xml2Json(communities))).type(MediaType.APPLICATION_JSON).build();
873
        }
874
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
875
                .type(MediaType.APPLICATION_JSON)
876
                .build();
877
    }
878

    
879
    @Path("/communities/{communityid}/categories")
880
    @GET
881
    @Produces(MediaType.APPLICATION_JSON)
882
    public Response fetchCommunityCategories(@PathParam("communityid") String communityid,
883
                                             @QueryParam("token") String token) throws ISLookUpServiceException {
884

    
885
        if(!JWTValidator.isValid(token)) {
886
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
887
                    .type(MediaType.APPLICATION_JSON)
888
                    .build();
889
        }
890
        if (Authorization.isRegistered(token)) {
891
            List<String> categories = lookupServiceLocator.getService().quickSearchProfile
892
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')//context[@id='" + communityid + "']//category[@claim=\'true\']\n" +
893
                            "return <category>{$x/@id}{$x/@label}</category>");
894

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

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

    
902
            xml2Json(categories);
903

    
904
            return Response.status(200).entity(composeDataResponse(xml2Json(categories))).type(MediaType.APPLICATION_JSON).build();
905
        }
906
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
907
                .type(MediaType.APPLICATION_JSON)
908
                .build();
909
    }
910

    
911
    @Path("/categories/{categoryid}/concepts")
912
    @GET
913
    @Produces(MediaType.APPLICATION_JSON)
914
    public Response fetchCategoryConcepts(@PathParam("categoryid") String categoryid,
915
                                          @QueryParam("token") String token) throws ISLookUpServiceException {
916
        if(!JWTValidator.isValid(token)) {
917
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
918
                    .type(MediaType.APPLICATION_JSON)
919
                    .build();
920
        }
921
        if (Authorization.isRegistered(token)) {
922
            List<String> concepts = lookupServiceLocator.getService().quickSearchProfile
923
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType') return $x//category[@id='" + categoryid + "']//concept");
924

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

    
929
            return Response.status(200).entity(composeDataResponse(xml2Json(concepts))).type(MediaType.APPLICATION_JSON).build();
930
        }
931
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
932
                .type(MediaType.APPLICATION_JSON)
933
                .build();
934
    }
935

    
936
    private String xml2Json(List<String> input) {
937
        StringBuilder builder = new StringBuilder();
938
        for(String category: input) {
939
            builder.append(category);
940
        }
941
        return builder.toString();
942
    }
943

    
944
    private String compose400Message(String message) {
945
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
946
    }
947

    
948
    private String compose400Message(String message, Exception exception) {
949
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
950
                "\"description\" : \""+  exception.getMessage() +"\" }";
951
    }
952

    
953
    private String compose403Message(String message) {
954
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
955
                "\"description\" : \"\" }";
956
    }
957

    
958
    private String compose404BulkDeleteMessage(String message, List<String> deletedIds, List<String> notFoundIds) {
959
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \""+  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
960
    }
961
    private String compose404Message(String message) {
962
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
963
    }
964

    
965
    private String compose400BulkInsertMessage(String message, List<String> insertedIds,JsonArray errorInClaims) {
966
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \""+  ", \"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
967
    }
968

    
969
    private String compose500Message(String message, Throwable throwable) {
970
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
971
                "\"description\" : \""+  throwable.getMessage() +"\" }";
972
    }
973

    
974
    private String compose500BulkInsertMessage(String message,  List<String> insertedIds, JsonArray errorInClaims) {
975
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
976
                "\"description\" : \""+   "\" , " +  "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
977
    }
978

    
979
    /*
980
    TODO check if needed
981
    private String compose500BulkDeleteMessage(String message,  List<String> deletedIds, List<String> notFoundIds, Exception exception) {
982
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
983
                "\"description\" : \""+  exception.getMessage() +"\" ," +  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
984
    }
985

    
986
    TODO check if needed
987
    private  String compose200Message(){
988
        return " { \"status\" : \"success\", \"code\": \"200\" }";
989
    }
990

    
991
    TODO check if needed
992
    private  String compose204Message(){
993
        return " { \"status\" : \"success\", \"code\": \"204\" }";
994
    } */
995

    
996
    private  String compose204BulkDeleteMessage(List<String> deletedIds, List<String> notFoundIds){
997
        return " { \"status\" : \"success\", \"code\": \"204\", "+ "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + "}";
998
    }
999

    
1000

    
1001
    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
1002
        String url = request.getRequestURL().toString();
1003
        //String query = request.getQueryString();
1004

    
1005
        return " { \"status\" : \"success\", \"code\": \"201\", \"link\": \"" + url  +"/"+ claimId +"\" }";
1006
    }
1007
    private  String compose201BulkInsertMessage(List<String> insertedIds, JsonArray errorInClaims){
1008
        //String url = request.getRequestURL().toString();
1009
        //String query = request.getQueryString();
1010

    
1011
        return " { \"status\" : \"success\", \"code\": \"201\","+ "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims)+ "}";
1012
    }
1013
    private String composeDataResponse(HttpServletRequest request, List<Claim> claims, int total, int offset, int limit) {
1014
        return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", " + composePaging(request, total, offset, limit) + ", "
1015
                + "\"data\" : " + new Gson().toJson(claims) + " }";
1016
    }
1017

    
1018
    private String composeDataResponse(String xml) {
1019
        return " { \"status\" : \"success\", \"code\": \"200\", "
1020
                + "\"data\" : " + XML.toJSONObject(xml).toString() + " }";
1021
    }
1022

    
1023
    private String composeDataResponse(Claim claim) {
1024
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(claim) + " }";
1025
    }
1026

    
1027
    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
1028
        logger.info("total " + total);
1029
        logger.info("currentOffset " + currentOffset);
1030
        logger.info("limit " + limit);
1031

    
1032
        String url = request.getRequestURL().toString();
1033
        //String query = request.getQueryString();
1034

    
1035
        String first = url+"?offset=0&limit=20";
1036

    
1037
        int previousPage;
1038
        int nextPage;
1039
        int lastPage;
1040

    
1041
        if (total <= limit) {
1042
            lastPage = 0;
1043
        } else {
1044
            if(total%limit == 0) {
1045
                lastPage = total/limit-1;
1046
            } else {
1047
                lastPage = total/limit ;
1048
            }
1049
        }
1050
        String last = url+"?offset=" + lastPage + "&limit=20";
1051

    
1052
        if (currentOffset-1 <= 0) {
1053
            previousPage = 0;
1054
        } else {
1055
            previousPage = currentOffset-1;
1056
        }
1057
        String previous = url+"?offset=" + previousPage + "&limit=20";
1058

    
1059
        if (currentOffset+1 >= lastPage) {
1060
            nextPage = lastPage;
1061

    
1062
        } else {
1063
            nextPage = currentOffset + 1;
1064
        }
1065
        String next = url+"?offset=" + nextPage + "&limit=20";
1066

    
1067
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + first +"\"}, {\"rel\":\"last\", \"href\":\"" + last + "\"}, {\"rel\":\"previous\", \"href\": \"" + previous + "\"}, {\"rel\":\"next\", \"href\":\"" +  next +"\"}"+ "]";
1068
    }
1069
    private String composeTotalResults(int total) {
1070
        return "\"total\": \""+total+"\"";
1071
    }
1072

    
1073
     public static void main(String[] args) {
1074
/*        HelloWorldService helloWorldService = new HelloWorldService();
1075

    
1076

    
1077
       System.out.println(helloWorldService.composePaging2(100, 0, 20));
1078
        System.out.println(helloWorldService.composePaging2(100, 4, 20));
1079

    
1080
        System.out.println(helloWorldService.composePaging2(99, 4, 20));
1081
        System.out.println(helloWorldService.composePaging2(99, 4, 20));
1082

    
1083
        System.out.println(helloWorldService.composePaging2(85, 4, 20));
1084

    
1085
         System.out.println(helloWorldService.composePaging2(0, 4, 20));
1086
*/
1087
/*
1088
         EmailValidator emailValidator = EmailValidator.getInstance();
1089
         System.out.println(emailValidator.isValid("jate@gdddd"));
1090

    
1091
         InternetAddress emailAddr = null;
1092
         try {
1093
             emailAddr = new InternetAddress("jate@gdddd");
1094
             emailAddr.validate();
1095
         } catch (AddressException e) {
1096
             System.out.println("false");
1097
         }
1098
         System.out.println("true");
1099

    
1100
         ArrayList<String> insertedIds= new ArrayList<String>();
1101
         insertedIds.add("1");
1102
         insertedIds.add("2");
1103
         insertedIds.add("3");
1104
         System.out.println(helloWorldService.compose403Message("hello"));
1105

    
1106
*/
1107
    }
1108

    
1109
}
    (1-1/1)