Project

General

Profile

1 42275 katerina.i
package eu.dnetlib.openaire.rest;
2
3 45960 argiro.kok
import com.google.gson.*;
4 42708 katerina.i
import eu.dnetlib.api.enabling.ISLookUpService;
5
import eu.dnetlib.api.enabling.ISLookUpServiceException;
6 42291 katerina.i
import eu.dnetlib.data.claims.migration.ClaimValidationException;
7 42275 katerina.i
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 46887 sofia.balt
import eu.dnetlib.openaire.rest.authorization.Authorization;
11 46903 sofia.balt
import eu.dnetlib.openaire.rest.inputHandler.userHandler;
12 46789 sofia.balt
import eu.dnetlib.openaire.rest.security.JWTValidator;
13 42708 katerina.i
import gr.uoa.di.driver.util.ServiceLocator;
14 42277 katerina.i
import org.apache.commons.validator.EmailValidator;
15 42275 katerina.i
import org.apache.log4j.Logger;
16 42708 katerina.i
import org.json.JSONObject;
17
import org.json.XML;
18 42275 katerina.i
import org.springframework.beans.factory.annotation.Autowired;
19
import org.springframework.stereotype.Component;
20
21 42708 katerina.i
import javax.annotation.Resource;
22 42275 katerina.i
import javax.servlet.http.HttpServletRequest;
23
import javax.ws.rs.*;
24
import javax.ws.rs.core.Context;
25
import javax.ws.rs.core.MediaType;
26
import javax.ws.rs.core.Response;
27 42708 katerina.i
import java.util.ArrayList;
28 42275 katerina.i
import java.util.List;
29
30
/**
31
 * Created by kiatrop on 15/4/2016.
32
 */
33
@Component
34
@Path("/claimsService")
35
public class HelloWorldService {
36
37 46758 katerina.i
    private static final Logger logger = Logger.getLogger(HelloWorldService.class);
38 42275 katerina.i
39
    @Autowired
40
    private FetchClaimHandler fetchClaimHandler = null;
41
42 42708 katerina.i
    @Resource
43
    private ServiceLocator<ISLookUpService> lookupServiceLocator = null;
44
45 42275 katerina.i
    @Autowired
46
    private ClaimHandler claimHandler = null;
47 43441 katerina.i
48
49 42275 katerina.i
    @GET
50
    @Path("projects/{projectId}/claims")
51 43441 katerina.i
    @Produces(MediaType.APPLICATION_JSON)
52
    public Response getProjectClaims(@PathParam("projectId") String projectId,
53 42275 katerina.i
                           @DefaultValue("0") @QueryParam("offset") int offset,
54
                           @DefaultValue("20") @QueryParam("limit") int limit,
55 42763 argiro.kok
                           @DefaultValue("") @QueryParam("keyword") String keyword,
56
                           @DefaultValue("") @QueryParam("sortby") String orderby,
57
                           @DefaultValue("true") @QueryParam("descending") boolean descending,
58
                           @DefaultValue("") @QueryParam("types") String types,
59 46883 katerina.i
                                     @QueryParam("token") String token,
60 42275 katerina.i
                           @Context HttpServletRequest request) {
61
62 46888 sofia.balt
        if(!JWTValidator.isValid(token)) {
63
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
64
                    .type(MediaType.APPLICATION_JSON)
65
                    .build();
66 42275 katerina.i
        }
67 46888 sofia.balt
        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 42763 argiro.kok
            }
75 42275 katerina.i
76 46888 sofia.balt
            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 42275 katerina.i
        }
96 46889 sofia.balt
97 46888 sofia.balt
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
98
                .type(MediaType.APPLICATION_JSON)
99
                .build();
100 42275 katerina.i
    }
101
102 42277 katerina.i
103 42275 katerina.i
    @GET
104
    @Path("/contexts/{contextId}/claims")
105 43441 katerina.i
    @Produces(MediaType.APPLICATION_JSON)
106 42277 katerina.i
    public Response getContextClaims(@PathParam("contextId") String contextId,
107 42275 katerina.i
                           @DefaultValue("0") @QueryParam("offset") int offset,
108 42277 katerina.i
                           @DefaultValue("20") @QueryParam("limit") int limit,
109 42763 argiro.kok
                           @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 46883 katerina.i
                                     @QueryParam("token") String token,
114 42277 katerina.i
                                     @Context HttpServletRequest request) {
115 42275 katerina.i
116 46889 sofia.balt
        if(!JWTValidator.isValid(token)) {
117
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
118
                    .type(MediaType.APPLICATION_JSON)
119
                    .build();
120 42275 katerina.i
        }
121 46889 sofia.balt
        if(Authorization.isAdmin(token)) {
122
123
            int total = -1;
124
            if (contextId == null || contextId.isEmpty()) {
125
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
126
                        .type(MediaType.APPLICATION_JSON).build();
127 42763 argiro.kok
            }
128 42275 katerina.i
129 46889 sofia.balt
            List<Claim> claims = null;
130
            List<String> listTypes = new ArrayList<String>();
131
            String[] types_array = types.split(",");
132
            for (int i = 0; i < types_array.length; i++) {
133
                if (types_array[i].length() > 0) {
134
                    listTypes.add(types_array[i]);
135
                }
136
            }
137
            try {
138
                claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset, keyword, orderby, descending, listTypes);
139
                total = fetchClaimHandler.countClaimsByContext(contextId, keyword, listTypes);
140
141
            } catch (Exception e) {
142
                logger.error("Could not fetch claims for context with id " + contextId, e);
143
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
144
                        " for context with id " + contextId + ".", e)).type(MediaType.APPLICATION_JSON).build();
145
            }
146
147
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
148 42275 katerina.i
        }
149
150 46889 sofia.balt
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
151
                .type(MediaType.APPLICATION_JSON)
152
                .build();
153 42275 katerina.i
    }
154
155 42277 katerina.i
156 42275 katerina.i
    @GET
157
    @Path("/results/{resultId}/claims")
158 43441 katerina.i
    @Produces(MediaType.APPLICATION_JSON)
159 42275 katerina.i
    public Response getResultClaims(@PathParam("resultId") String resultId,
160 42277 katerina.i
                                    @DefaultValue("0") @QueryParam("offset") int offset,
161
                                    @DefaultValue("20") @QueryParam("limit") int limit,
162 42763 argiro.kok
                                    @DefaultValue("") @QueryParam("keyword") String keyword,
163
                                    @DefaultValue("") @QueryParam("sortby") String orderby,
164
                                    @DefaultValue("true") @QueryParam("descending") boolean descending,
165
                                    @DefaultValue("") @QueryParam("types") String types,
166 46883 katerina.i
                                    @QueryParam("token") String token,
167 42277 katerina.i
                                    @Context HttpServletRequest request) {
168 42275 katerina.i
169 46890 sofia.balt
        if(!JWTValidator.isValid(token)) {
170
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
171
                    .type(MediaType.APPLICATION_JSON)
172
                    .build();
173 42275 katerina.i
        }
174 46890 sofia.balt
        if(Authorization.isAdmin(token)) {
175
176
            int total = -1;
177
            if (resultId == null || resultId.isEmpty()) {
178
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
179
                        .type(MediaType.APPLICATION_JSON).build();
180 42763 argiro.kok
            }
181 46887 sofia.balt
182 46890 sofia.balt
            List<Claim> claims = null;
183
            List<String> listTypes = new ArrayList<String>();
184
            String[] types_array = types.split(",");
185
            for (int i = 0; i < types_array.length; i++) {
186
                if (types_array[i].length() > 0) {
187
                    listTypes.add(types_array[i]);
188
                }
189
            }
190 42275 katerina.i
191 46890 sofia.balt
            try {
192
                claims = fetchClaimHandler.fetchClaimsByResult(resultId, limit, offset, keyword, orderby, descending, listTypes);
193
                total = fetchClaimHandler.countClaimsByResult(resultId, keyword, listTypes);
194
195
            } catch (Exception e) {
196
                logger.error("Could not fetch claims for result with id " + resultId, e);
197
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
198
                        " for result with id " + resultId + ".", e)).type(MediaType.APPLICATION_JSON).build();
199
            }
200
201
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
202 42275 katerina.i
        }
203
204 46890 sofia.balt
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
205
                .type(MediaType.APPLICATION_JSON)
206
                .build();
207 42275 katerina.i
    }
208
209
210
    @GET
211 42277 katerina.i
    @Path("/users/{userMail}/claims")
212 43441 katerina.i
    @Produces(MediaType.APPLICATION_JSON)
213 42275 katerina.i
    public Response getUserClaims(@PathParam("userMail") String userMail,
214 46883 katerina.i
                                  @DefaultValue("0") @QueryParam("offset") int offset,
215
                                  @DefaultValue("20") @QueryParam("limit") int limit,
216
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
217
                                  @DefaultValue("") @QueryParam("sortby") String orderby,
218
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
219
                                  @DefaultValue("") @QueryParam("types") String types,
220
                                  @QueryParam("token") String token,
221
                                  @Context HttpServletRequest request) {
222 42275 katerina.i
223 42277 katerina.i
224 46891 sofia.balt
        if(!JWTValidator.isValid(token)) {
225
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
226
                    .type(MediaType.APPLICATION_JSON)
227
                    .build();
228 42275 katerina.i
        }
229 46891 sofia.balt
        if(Authorization.isRegistered(token)) {
230 42277 katerina.i
231 46891 sofia.balt
            int total = -1;
232
            EmailValidator emailValidator = EmailValidator.getInstance();
233
234
            if (userMail == null || userMail.isEmpty()) {
235
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
236
                        .type(MediaType.APPLICATION_JSON).build();
237 42763 argiro.kok
            }
238 42275 katerina.i
239 46891 sofia.balt
            if (!emailValidator.isValid(userMail)) {
240
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is not valid."))
241
                        .type(MediaType.APPLICATION_JSON).build();
242
            }
243
244
            List<Claim> claims = null;
245
            List<String> listTypes = new ArrayList<String>();
246
            String[] types_array = types.split(",");
247
            for (int i = 0; i < types_array.length; i++) {
248
                if (types_array[i].length() > 0) {
249
                    listTypes.add(types_array[i]);
250
                }
251
            }
252
            try {
253
                claims = fetchClaimHandler.fetchClaimsByUser(userMail, limit, offset, keyword, orderby, descending, listTypes);
254
                total = fetchClaimHandler.countClaimsByUser(userMail, keyword, listTypes);
255
256
            } catch (Exception e) {
257
                logger.error("Could not fetch claims for result with id " + userMail, e);
258
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
259
                        " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
260
            }
261
262
            return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
263 42275 katerina.i
        }
264 46891 sofia.balt
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
265
                .type(MediaType.APPLICATION_JSON)
266
                .build();
267 42275 katerina.i
    }
268
269
270
    @GET
271
    @Path("/claims/{claimId}")
272 43441 katerina.i
    @Produces(MediaType.APPLICATION_JSON)
273 42275 katerina.i
    public Response getClaimsById(@PathParam("claimId") String claimId,
274
                                  @DefaultValue("0") @QueryParam("offset") int offset,
275 42277 katerina.i
                                  @DefaultValue("20") @QueryParam("limit") int limit,
276 46883 katerina.i
                                  @QueryParam("token") String token,
277 42277 katerina.i
                                  @Context HttpServletRequest request) {
278 42275 katerina.i
279 46917 sofia.balt
        if(!JWTValidator.isValid(token)) {
280
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
281
                    .type(MediaType.APPLICATION_JSON)
282
                    .build();
283
        }
284
        if(Authorization.isRegistered(token)) {
285 42275 katerina.i
286 46917 sofia.balt
            List<Claim> claims = null;
287 42275 katerina.i
288 46917 sofia.balt
            int total = -1;
289
            if (claimId == null || claimId.isEmpty()) {
290
                try {
291
                    claims = fetchClaimHandler.fetchAllClaims(limit, offset);
292
                    total = fetchClaimHandler.countAllClaims("", new ArrayList<String>());
293 42277 katerina.i
294 46917 sofia.balt
                    return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).type(MediaType.APPLICATION_JSON).build();
295 42275 katerina.i
296 46917 sofia.balt
                } catch (Exception e) {
297
                    logger.error("Could not fetch claims.", e);
298
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
299
                            .type(MediaType.APPLICATION_JSON).build();
300
                }
301 42277 katerina.i
            }
302 42275 katerina.i
303 46917 sofia.balt
            try {
304
                Claim claim = fetchClaimHandler.fetchClaimById(claimId);
305
                if (claim == null) {
306
                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Cannot find claim with id " + claimId + "."))
307
                            .type(MediaType.APPLICATION_JSON).build();
308
                }
309 42277 katerina.i
310 46917 sofia.balt
                return Response.status(200).entity(composeDataResponse(request, claim, total, offset, limit)).build();
311
312
            } catch (Exception e) {
313
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claim " +
314
                        "with id " + claimId + " id.", e)).type(MediaType.APPLICATION_JSON).build();
315
            }
316 42275 katerina.i
        }
317 46917 sofia.balt
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
318
                .type(MediaType.APPLICATION_JSON)
319
                .build();
320 42275 katerina.i
    }
321
322 42277 katerina.i
    @GET
323
    @Path("/claims")
324 43441 katerina.i
    @Produces(MediaType.APPLICATION_JSON)
325 46789 sofia.balt
    public Response getAllClaims(@DefaultValue("0") @QueryParam("offset") int offset,
326 42277 katerina.i
                                  @DefaultValue("20") @QueryParam("limit") int limit,
327 42763 argiro.kok
                                  @DefaultValue("") @QueryParam("keyword") String keyword,
328
                                  @DefaultValue("date") @QueryParam("sortby") String orderby,
329
                                  @DefaultValue("true") @QueryParam("descending") boolean descending,
330
                                  @DefaultValue("") @QueryParam("types") String types,
331 46789 sofia.balt
                                  @QueryParam("token") String token,
332 42277 katerina.i
                                  @Context HttpServletRequest request) {
333 42275 katerina.i
334 46789 sofia.balt
        if(!JWTValidator.isValid(token)) {
335 46806 sofia.balt
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
336
                    .type(MediaType.APPLICATION_JSON)
337
                    .build();
338 46789 sofia.balt
        }
339 46887 sofia.balt
        if(Authorization.isAdmin(token)) {
340
341
            List<Claim> claims = null;
342
            List<String> listTypes = new ArrayList<String>();
343
            String[] types_array = types.split(",");
344
            for (int i = 0; i < types_array.length; i++) {
345
                if (types_array[i].length() > 0) {
346
                    listTypes.add(types_array[i]);
347
                }
348 42763 argiro.kok
            }
349 46887 sofia.balt
            logger.debug("Types: " + listTypes.toString());
350 42277 katerina.i
351 46887 sofia.balt
            int total = -1;
352
            try {
353
                claims = fetchClaimHandler.fetchAllClaims(limit, offset, keyword, orderby, descending, listTypes);
354
                total = fetchClaimHandler.countAllClaims(keyword, listTypes);
355 42277 katerina.i
356 46887 sofia.balt
                return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
357 42277 katerina.i
358 46887 sofia.balt
            } catch (Exception e) {
359
                logger.error("Could not fetch claims.", e);
360
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
361
                        .type(MediaType.APPLICATION_JSON).build();
362
            }
363 42277 katerina.i
        }
364 46888 sofia.balt
365
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access"))
366
               .type(MediaType.APPLICATION_JSON)
367
               .build();
368 42277 katerina.i
    }
369
370 42291 katerina.i
371 45960 argiro.kok
    @POST
372 42275 katerina.i
    @Path("/claims/{claimId}")
373 43441 katerina.i
    @Produces(MediaType.APPLICATION_JSON)
374 46883 katerina.i
    public Response deleteClaim(@PathParam("claimId") String claimId,
375
                                @QueryParam("token") String token) {
376 42275 katerina.i
377 46917 sofia.balt
        if(!JWTValidator.isValid(token)) {
378
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
379
                    .type(MediaType.APPLICATION_JSON)
380
                    .build();
381
        }
382 46903 sofia.balt
        try {
383 42275 katerina.i
384 46917 sofia.balt
            if (Authorization.isRegistered(token) && (userHandler.getMail(token).equals(fetchClaimHandler.fetchClaimById(claimId).getUserMail()))) {
385 46903 sofia.balt
                if (claimId == null || claimId.isEmpty()) {
386
                    return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
387
                            .type(MediaType.APPLICATION_JSON).build();
388 46892 sofia.balt
                }
389
390 46903 sofia.balt
                try {
391
                    if (claimHandler.deleteClaim(claimId)) {
392
                        return Response.status(204).entity(compose204Message()).type(MediaType.APPLICATION_JSON).build();
393
                    }
394
395
                } catch (Exception e) {
396
                    logger.error("Fail to delete claim with id " + claimId + ".", e);
397
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId + ".", e))
398
                            .type(MediaType.APPLICATION_JSON).build();
399
                }
400
401
                return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
402 46892 sofia.balt
                        .type(MediaType.APPLICATION_JSON).build();
403 42291 katerina.i
            }
404 42275 katerina.i
405 46906 sofia.balt
            return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
406 46903 sofia.balt
                    .type(MediaType.APPLICATION_JSON)
407
                    .build();
408
409
        } catch (Exception e) {
410
            logger.error("Could not fetch claims.", e);
411
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
412 42275 katerina.i
                    .type(MediaType.APPLICATION_JSON).build();
413
        }
414
    }
415 42763 argiro.kok
/*
416 42275 katerina.i
417 42763 argiro.kok
    @DELETE
418
    @Path("/claims/{claimId}")
419
    public Response deleteClaim(@PathParam("claimId") String claimId) {
420 42275 katerina.i
421 42763 argiro.kok
        if (claimId == null || claimId.isEmpty()) {
422
            return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
423
                    .header("Access-Control-Allow-Methods", "DELETE")
424
                    .type(MediaType.APPLICATION_JSON).build();
425
        }
426 42291 katerina.i
427 42763 argiro.kok
        try {
428
            if(claimHandler.deleteClaim(claimId)) {
429
                return Response.status(204).entity(compose204Message()).header("Access-Control-Allow-Origin", "*")
430
                        .header("Access-Control-Allow-Methods", "DELETE").type(MediaType.APPLICATION_JSON).build();
431
            }
432
433 46887 sofia.balt
        } catch (Exception e) {return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
434
                    .type(MediaType.APPLICATION_JSON)
435
                    .build();
436 42763 argiro.kok
            logger.error("Fail to delete claim with id " + claimId + ".", e);
437
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId +".", e))
438
                    .header("Access-Control-Allow-Origin", "*")
439
                    .header("Access-Control-Allow-Methods", "DELETE")
440
                    .type(MediaType.APPLICATION_JSON).build();
441
        }
442
443
        return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty.")).header("Access-Control-Allow-Origin", "*")
444
                .header("Access-Control-Allow-Methods", "DELETE")
445
                .type(MediaType.APPLICATION_JSON).build();
446
    }
447
 */
448 45960 argiro.kok
@DELETE
449
@Path("/claims/bulk")
450
@Produces(MediaType.APPLICATION_JSON)
451 46883 katerina.i
public Response deleteBulkClaims(@QueryParam("claimId") List<String> claimIds,
452
                                 @QueryParam("token") String token) {
453 46917 sofia.balt
454
    if(!JWTValidator.isValid(token)) {
455
        return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
456
                .type(MediaType.APPLICATION_JSON)
457
                .build();
458
    }
459
460 46789 sofia.balt
    ArrayList<String> deletedIds= new ArrayList<String>();
461
    ArrayList<String> notFoundIds= new ArrayList<String>();
462 45960 argiro.kok
    logger.debug("Trying to delete claims with ids: " + claimIds.toString() + ".");
463
    if (claimIds == null || claimIds.size() == 0) {
464
        return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
465
                .type(MediaType.APPLICATION_JSON).build();
466
    }
467 42763 argiro.kok
468 45960 argiro.kok
    for (String claimId : claimIds) {
469
        try {
470 46906 sofia.balt
471 46917 sofia.balt
            if (Authorization.isRegistered(token)) {
472 46906 sofia.balt
                if (userHandler.getMail(token).equals(fetchClaimHandler.fetchClaimById(claimId).getUserMail())) {
473
                    if (claimHandler.deleteClaim(claimId)) {
474
                        deletedIds.add(claimId);
475
                    } else {
476
                        notFoundIds.add(claimId);
477
                    }
478
                } else {
479
                    return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to delete."))
480
                            .type(MediaType.APPLICATION_JSON)
481
                            .build();
482
                }
483 45960 argiro.kok
            } else {
484 46906 sofia.balt
                return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. Maybe you are not registered."))
485
                        .type(MediaType.APPLICATION_JSON)
486
                        .build();
487 45960 argiro.kok
            }
488
        } catch (Exception e) {
489
            logger.error("Fail to delete claim with id " + claimId + ".", e);
490
            notFoundIds.add(claimId);
491
        }
492
    }
493
    logger.debug("Successfully deleted " + deletedIds.size() + " from " + claimIds.size()  +". Deleted claims with ids: " + deletedIds.toString() + ".");
494
    if (claimIds.size() == notFoundIds.size()) {
495
        return Response.status(Response.Status.NOT_FOUND).entity(compose404BulkDeleteMessage("Claim ids cannot be empty.",deletedIds,notFoundIds))
496
                .type(MediaType.APPLICATION_JSON).build();
497
    } else if (claimIds.size() == notFoundIds.size()) {
498
        return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
499
    } else {
500
        return Response.status(204).entity(compose204BulkDeleteMessage(deletedIds,notFoundIds)).type(MediaType.APPLICATION_JSON).build();
501
    }
502
}
503
504 42275 katerina.i
    @POST
505 42291 katerina.i
    @Path("/claims")
506 42275 katerina.i
    @Produces(MediaType.APPLICATION_JSON)
507
    @Consumes(MediaType.APPLICATION_JSON)
508 46883 katerina.i
    public Response addClaim(String input, @Context HttpServletRequest request,
509
                             @QueryParam("token") String token) {
510 42291 katerina.i
511 46917 sofia.balt
        if(!JWTValidator.isValid(token)) {
512
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
513
                    .type(MediaType.APPLICATION_JSON)
514
                    .build();
515
        }
516
        if(Authorization.isRegistered(token)) {
517
            JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
518 42275 katerina.i
519 46917 sofia.balt
            String claimedBy = jsonObject.get("claimedBy").getAsString();
520
            logger.info("claimedBy " + claimedBy);
521 42291 katerina.i
522 46917 sofia.balt
            String sourceId = jsonObject.get("sourceId").getAsString();
523
            logger.info("sourceId " + sourceId);
524
            String sourceType = jsonObject.get("sourceType").getAsString();
525
            logger.info("sourceType " + sourceType);
526
            String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
527
            logger.info("sourceCollectedFrom " + sourceCollectedFrom);
528
            String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
529
            logger.info("sourceAccessRights " + sourceAccessRights);
530
            String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
531
            sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
532
            logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
533 42275 katerina.i
534 46917 sofia.balt
            String targetId = jsonObject.get("targetId").getAsString();
535
            logger.info("targetId " + targetId);
536
            String targetType = jsonObject.get("targetType").getAsString();
537
            logger.info("targetType " + targetType);
538
            String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
539
            logger.info("targetCollectedFrom " + targetCollectedFrom);
540
            String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
541
            logger.info("targetAccessRights " + targetAccessRights);
542
            String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
543
            targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
544
            logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
545 42275 katerina.i
546 46917 sofia.balt
            EmailValidator emailValidator = EmailValidator.getInstance();
547
            if (!emailValidator.isValid(claimedBy)) {
548
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
549
                        .type(MediaType.APPLICATION_JSON).build();
550
            }
551 42291 katerina.i
552
553 46917 sofia.balt
            try {
554
                String claimId = claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate);
555
                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
556 42275 katerina.i
557 46917 sofia.balt
            } catch (ClaimValidationException ve) {
558
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
559
                        .type(MediaType.APPLICATION_JSON).build();
560 42291 katerina.i
561 46917 sofia.balt
            } catch (Exception e) {
562
                logger.error("Fail to add new claim.", e);
563
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
564
                        .type(MediaType.APPLICATION_JSON).build();
565
            }
566 42275 katerina.i
        }
567 46917 sofia.balt
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access."))
568
                .type(MediaType.APPLICATION_JSON)
569
                .build();
570 42291 katerina.i
    }
571 42275 katerina.i
572 45960 argiro.kok
    @POST
573
    @Path("/claims/bulk")
574
    @Produces(MediaType.APPLICATION_JSON)
575
    @Consumes(MediaType.APPLICATION_JSON)
576 46883 katerina.i
    public Response addBulkClaims(String input, @Context HttpServletRequest request,
577
                                  @QueryParam("token") String token) {
578 45960 argiro.kok
579 46917 sofia.balt
        if(!JWTValidator.isValid(token)) {
580
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
581
                    .type(MediaType.APPLICATION_JSON)
582
                    .build();
583
        }
584 46893 sofia.balt
        if (Authorization.isRegistered(token)) {
585
            ArrayList<String> insertedIds = new ArrayList<String>();
586
            JsonArray errorInClaims = new JsonArray();
587
            int code200 = 0;
588
            int code400 = 0;
589
            int code500 = 0;
590
            JsonArray jsonArray = new JsonParser().parse(input).getAsJsonArray();
591
            for (JsonElement je : jsonArray) {
592
                JsonObject jsonObject = je.getAsJsonObject();
593 45960 argiro.kok
594 46893 sofia.balt
                logger.info("targetId " + jsonObject.toString());
595
                String claimedBy = jsonObject.get("claimedBy").getAsString();
596
                logger.info("claimedBy " + claimedBy);
597 45960 argiro.kok
598 46893 sofia.balt
                String sourceId = jsonObject.get("sourceId").getAsString();
599
                logger.info("sourceId " + sourceId);
600
                String sourceType = jsonObject.get("sourceType").getAsString();
601
                logger.info("sourceType " + sourceType);
602
                String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
603
                logger.info("sourceCollectedFrom " + sourceCollectedFrom);
604
                String sourceAccessRights = jsonObject.get("sourceAccessRights").getAsString();
605
                logger.info("sourceAccessRights " + sourceAccessRights);
606
                String sourceEmbargoEndDate = jsonObject.get("sourceEmbargoEndDate").getAsString();
607
                sourceEmbargoEndDate = (sourceEmbargoEndDate != null && sourceEmbargoEndDate.equals("")) ? null : sourceEmbargoEndDate;
608
                logger.info("sourceEmbargoEndDate " + sourceEmbargoEndDate);
609 45960 argiro.kok
610 46893 sofia.balt
                String targetId = jsonObject.get("targetId").getAsString();
611
                logger.info("targetId " + targetId);
612
                String targetType = jsonObject.get("targetType").getAsString();
613
                logger.info("targetType " + targetType);
614
                String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
615
                logger.info("targetCollectedFrom " + targetCollectedFrom);
616
                String targetAccessRights = jsonObject.get("targetAccessRights").getAsString();
617
                logger.info("targetAccessRights " + targetAccessRights);
618
                String targetEmbargoEndDate = jsonObject.get("targetEmbargoEndDate").getAsString();
619
                targetEmbargoEndDate = (targetEmbargoEndDate != null && targetEmbargoEndDate.equals("")) ? null : targetEmbargoEndDate;
620
                logger.info("targetEmbargoEndDate " + targetEmbargoEndDate);
621 45960 argiro.kok
622 46893 sofia.balt
                EmailValidator emailValidator = EmailValidator.getInstance();
623
                if (!emailValidator.isValid(claimedBy)) {
624
                    jsonObject.addProperty("error", "user");
625
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail is invalid."))
626
                    //                        .type(MediaType.APPLICATION_JSON).build();
627
                    code400++;
628
                    errorInClaims.add(jsonObject);
629
                }
630 45960 argiro.kok
631
632 46893 sofia.balt
                try {
633
                    String claimId = claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, sourceAccessRights, sourceEmbargoEndDate, targetType, targetId, targetCollectedFrom, targetAccessRights, targetEmbargoEndDate);
634
                    insertedIds.add(claimId);
635
                    code200++;
636
                    //                return Response.status(200).entity(compose201PostMessage(request, claimId)).type(MediaType.APPLICATION_JSON).build();
637 45960 argiro.kok
638 46893 sofia.balt
                } catch (ClaimValidationException ve) {
639
                    //                return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("The given ids are wrong.", ve))
640
                    //                        .type(MediaType.APPLICATION_JSON).build();
641
                    jsonObject.addProperty("error", "validation");
642
                    errorInClaims.add(jsonObject);
643
                    code400++;
644
645
                } catch (Exception e) {
646
                    //                logger.error("Fail to add new claim.", e);
647
                    //                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
648
                    //                        .type(MediaType.APPLICATION_JSON).build();
649
                    jsonObject.addProperty("error", "insertion");
650
                    errorInClaims.add(jsonObject);
651
                    code500++;
652
                }
653 45960 argiro.kok
            }
654 46893 sofia.balt
            if (jsonArray.size() == code500) {
655
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500BulkInsertMessage("Fail to add new claim.", insertedIds, errorInClaims))
656
                        .type(MediaType.APPLICATION_JSON).build();
657
            } else if (code200 > 0) {
658
                return Response.status(200).entity(compose201BulkInsertMessage(request, insertedIds, errorInClaims)).type(MediaType.APPLICATION_JSON).build();
659
            } else {
660
                return Response.status(Response.Status.BAD_REQUEST).entity(compose400BulkInsertMessage("The given ids are wrong.", insertedIds, errorInClaims))
661
                        .type(MediaType.APPLICATION_JSON).build();
662
            }
663 45960 argiro.kok
        }
664 46893 sofia.balt
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
665
                .type(MediaType.APPLICATION_JSON)
666
                .build();
667 45960 argiro.kok
668
    }
669
670 42708 katerina.i
    @Path("/communities")
671 42275 katerina.i
    @GET
672
    @Produces(MediaType.APPLICATION_JSON)
673 46883 katerina.i
    public Response fetchCommunities(@QueryParam("token") String token) throws ISLookUpServiceException {
674 42275 katerina.i
675 46917 sofia.balt
        if(!JWTValidator.isValid(token)) {
676
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
677
                    .type(MediaType.APPLICATION_JSON)
678
                    .build();
679
        }
680 46894 sofia.balt
        if (Authorization.isRegistered(token)) {
681
            //it needs to have at lease one category with @claim=true
682
            List<String> communities = lookupServiceLocator.getService().quickSearchProfile
683
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')  \n" +
684
                            "                where $x//context[@type='community']//category[@claim='true'] \n" +
685
                            "            return <communities>{$x//context/@id}{$x//context/@label}</communities>");
686 42275 katerina.i
687 46894 sofia.balt
            return Response.status(200).entity(composeDataResponse(xml2Json(communities))).type(MediaType.APPLICATION_JSON).build();
688
        }
689
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
690
                .type(MediaType.APPLICATION_JSON)
691
                .build();
692 42708 katerina.i
    }
693
694
    @Path("/communities/{communityid}/categories")
695
    @GET
696
    @Produces(MediaType.APPLICATION_JSON)
697 46883 katerina.i
    public Response fetchCommunityCategories(@PathParam("communityid") String communityid,
698
                                             @QueryParam("token") String token) throws ISLookUpServiceException {
699 42708 katerina.i
700 46917 sofia.balt
        if(!JWTValidator.isValid(token)) {
701
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
702
                    .type(MediaType.APPLICATION_JSON)
703
                    .build();
704
        }
705 46894 sofia.balt
        if (Authorization.isRegistered(token)) {
706
            List<String> categories = lookupServiceLocator.getService().quickSearchProfile
707
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')//context[@id='" + communityid + "']//category[@claim=\'true\']\n" +
708
                            "return <category>{$x/@id}{$x/@label}</category>");
709 42708 katerina.i
710 46894 sofia.balt
            logger.info("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType')//context[@id='" + communityid + "']//category[@claim=\'true\']\n" +
711
                    "return <category>{$x/@id}{$x/@label}</category>");
712 42708 katerina.i
713 46894 sofia.balt
            if (categories == null || categories.isEmpty()) {
714
                return Response.status(404).entity(compose404Message("There are no categories for community with id " + communityid)).type(MediaType.APPLICATION_JSON).build();
715
            }
716 42724 katerina.i
717 46894 sofia.balt
            xml2Json(categories);
718
719
            return Response.status(200).entity(composeDataResponse(xml2Json(categories))).type(MediaType.APPLICATION_JSON).build();
720
        }
721
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
722
                .type(MediaType.APPLICATION_JSON)
723
                .build();
724 42275 katerina.i
    }
725
726 42708 katerina.i
    @Path("/categories/{categoryid}/concepts")
727
    @GET
728
    @Produces(MediaType.APPLICATION_JSON)
729 46883 katerina.i
    public Response fetchCategoryConcepts(@PathParam("categoryid") String categoryid,
730
                                          @QueryParam("token") String token) throws ISLookUpServiceException {
731 46917 sofia.balt
        if(!JWTValidator.isValid(token)) {
732
            return Response.status(Response.Status.UNAUTHORIZED).entity(compose404Message("Not valid Token"))
733
                    .type(MediaType.APPLICATION_JSON)
734
                    .build();
735
        }
736 46895 sofia.balt
        if (Authorization.isRegistered(token)) {
737
            List<String> concepts = lookupServiceLocator.getService().quickSearchProfile
738
                    ("for $x in collection('/db/DRIVER/ContextDSResources/ContextDSResourceType') return $x//category[@id='" + categoryid + "']//concept");
739 42708 katerina.i
740 46895 sofia.balt
            if (concepts == null || concepts.isEmpty()) {
741
                return Response.status(404).entity(compose404Message("There are no concepts for category with id " + categoryid)).type(MediaType.APPLICATION_JSON).build();
742
            }
743 42708 katerina.i
744 46895 sofia.balt
            return Response.status(200).entity(composeDataResponse(xml2Json(concepts))).type(MediaType.APPLICATION_JSON).build();
745
        }
746
        return Response.status(Response.Status.FORBIDDEN).entity(compose403Message("Forbidden: You don't have permission to access. You are not registered."))
747
                .type(MediaType.APPLICATION_JSON)
748
                .build();
749 42708 katerina.i
    }
750
751 42724 katerina.i
    private String xml2Json(List<String> input) {
752
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
753
        StringBuilder builder = new StringBuilder();
754
        for(String category: input) {
755
            builder.append(category);
756
        }
757
        return builder.toString();
758
    }
759
760 42275 katerina.i
    private String compose400Message(String message) {
761
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
762
    }
763
764 42291 katerina.i
    private String compose400Message(String message, Exception exception) {
765
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
766
                "\"description\" : \""+  exception.getMessage() +"\" }";
767
    }
768
769 46887 sofia.balt
    private String compose403Message(String message) {
770
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +"\", " +
771
                "\"description\" : \" }";
772
    }
773
774 45960 argiro.kok
    private String compose404BulkDeleteMessage(String message, ArrayList<String> deletedIds, ArrayList<String> notFoundIds) {
775
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \""+  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
776
    }
777 42275 katerina.i
    private String compose404Message(String message) {
778
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
779
    }
780
781 45960 argiro.kok
    private String compose400BulkInsertMessage(String message, ArrayList<String> insertdIds,JsonArray errorInClaims) {
782
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \""+  ", \"insertdIds\" : " + new Gson().toJson(insertdIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
783
    }
784
785 42275 katerina.i
    private String compose500Message(String message, Exception exception) {
786
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
787
                "\"description\" : \""+  exception.getMessage() +"\" }";
788
    }
789
790 45960 argiro.kok
    private String compose500BulkInsertMessage(String message,  ArrayList<String> insertdIds, JsonArray errorInClaims) {
791
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
792
                "\"description\" : \""+   "\" , " +  "\"insertdIds\" : " + new Gson().toJson(insertdIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims) + " }";
793
    }
794
    private String compose500BulkDeleteMessage(String message,  ArrayList<String> deletedIds, ArrayList<String> notFoundIds, Exception exception) {
795
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
796
                "\"description\" : \""+  exception.getMessage() +"\" ," +  "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + " }";
797
    }
798 42275 katerina.i
    private  String compose200Message(){
799
        return " { \"status\" : \"success\", \"code\": \"200\" }";
800
    }
801
802 42291 katerina.i
    private  String compose204Message(){
803
        return " { \"status\" : \"success\", \"code\": \"204\" }";
804
    }
805 45960 argiro.kok
    private  String compose204BulkDeleteMessage(ArrayList<String> deletedIds, ArrayList<String> notFoundIds){
806
        return " { \"status\" : \"success\", \"code\": \"204\", "+ "\"deletedIds\" : " + new Gson().toJson(deletedIds) +","+  "\"notFoundIds\" : " + new Gson().toJson(notFoundIds) + "}";
807
    }
808 42291 katerina.i
809 45960 argiro.kok
810 42291 katerina.i
    private  String compose201PostMessage(@Context HttpServletRequest request, String claimId){
811 42275 katerina.i
        String url = request.getRequestURL().toString();
812 42291 katerina.i
        //String query = request.getQueryString();
813 42275 katerina.i
814 42763 argiro.kok
        return " { \"status\" : \"success\", \"code\": \"201\", \"link\": \"" + url  +"/"+ claimId +"\" }";
815 42275 katerina.i
    }
816 45960 argiro.kok
    private  String compose201BulkInsertMessage(@Context HttpServletRequest request, ArrayList<String> insertedIds, JsonArray errorInClaims){
817
        String url = request.getRequestURL().toString();
818
        //String query = request.getQueryString();
819 42275 katerina.i
820 45960 argiro.kok
        return " { \"status\" : \"success\", \"code\": \"201\","+ "\"insertedIds\" : " + new Gson().toJson(insertedIds) +","+  "\"errorInClaims\" : " + new Gson().toJson(errorInClaims)+ "}";
821
    }
822 42275 katerina.i
    private String composeDataResponse(HttpServletRequest request, List<Claim> claims, int total, int offset, int limit) {
823 42763 argiro.kok
        return " { \"status\" : \"success\", \"code\": \"200\",  "+composeTotalResults(total)+", " + composePaging(request, total, offset, limit) + ", "
824 42275 katerina.i
                + "\"data\" : " + new Gson().toJson(claims) + " }";
825
    }
826
827 42708 katerina.i
    private String composeDataResponse(String xml) {
828
        return " { \"status\" : \"success\", \"code\": \"200\", "
829
                + "\"data\" : " + XML.toJSONObject(xml).toString() + " }";
830
    }
831
832 42277 katerina.i
    private String composeDataResponse(HttpServletRequest request, Claim claim, int total, int offset, int limit) {
833
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(claim) + " }";
834
    }
835
836 46758 katerina.i
    private static String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
837 42277 katerina.i
        logger.info("total " + total);
838
        logger.info("currentOffset " + currentOffset);
839
        logger.info("limit " + limit);
840
841 42275 katerina.i
        String url = request.getRequestURL().toString();
842 42277 katerina.i
        //String query = request.getQueryString();
843 42275 katerina.i
844 42277 katerina.i
        String first = url+"?offset=0&limit=20";
845 42275 katerina.i
846
        int previousPage;
847
        int nextPage;
848
        int lastPage;
849
850 42277 katerina.i
        if (total <= limit) {
851 42275 katerina.i
            lastPage = 0;
852
        } else {
853
            if(total%limit == 0) {
854
                lastPage = total/limit-1;
855
            } else {
856
                lastPage = total/limit ;
857
            }
858
        }
859 42277 katerina.i
        String last = url+"?offset=" + lastPage + "&limit=20";
860 42275 katerina.i
861 42277 katerina.i
        if (currentOffset-1 <= 0) {
862 42275 katerina.i
            previousPage = 0;
863
        } else {
864
            previousPage = currentOffset-1;
865
        }
866 42277 katerina.i
        String previous = url+"?offset=" + previousPage + "&limit=20";
867 42275 katerina.i
868 42277 katerina.i
        if (currentOffset+1 >= lastPage) {
869 42275 katerina.i
            nextPage = lastPage;
870
871
        } else {
872
            nextPage = currentOffset + 1;
873
        }
874 42277 katerina.i
        String next = url+"?offset=" + nextPage + "&limit=20";
875 42275 katerina.i
876
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + first +"\"}, {\"rel\":\"last\", \"href\":\"" + last + "\"}, {\"rel\":\"previous\", \"href\": \"" + previous + "\"}, {\"rel\":\"next\", \"href\":\"" +  next +"\"}"+ "]";
877
    }
878 42763 argiro.kok
    private String composeTotalResults(int total) {
879
        return "\"total\": \""+total+"\"";
880
    }
881 42275 katerina.i
882 42277 katerina.i
    private String composePaging2( int total, int currentOffset, int limit) {
883
       // String url = request.getRequestURL().toString();
884
        //String query = request.getQueryString();
885 42275 katerina.i
886 42277 katerina.i
        //String first = url+"?offset=0&limit=20";
887
888
        int previousPage;
889
        int nextPage;
890
        int lastPage;
891
892
        if (total < currentOffset) {
893
            lastPage = 0;
894
        } else {
895
            if(total%limit == 0) {
896
                lastPage = total/limit-1;
897
            } else {
898
                lastPage = total/limit ;
899
            }
900
        }
901
        //String last = url+"?offset=" + lastPage + "&limit=20";
902
903
        if (currentOffset-1 <= 0) {
904
            previousPage = 0;
905
        } else {
906
            previousPage = currentOffset-1;
907
        }
908
        //String previous = url+"?offset=" + previousPage + "&limit=20";
909
910
        if (currentOffset+1 >= lastPage) {
911
            nextPage = lastPage;
912
913
        } else {
914
            nextPage = currentOffset + 1;
915
        }
916
        //String next = url+"?offset=" + nextPage + "&limit=20";
917
918
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + 0 +"\"}, {\"rel\":\"last\", \"href\":\"" + lastPage + "\"}, {\"rel\":\"previous\", \"href\": \"" + previousPage + "\"}, {\"rel\":\"next\", \"href\":\"" +  nextPage +"\"}"+ "]";
919
    }
920
921
     public static void main(String[] args) {
922 42275 katerina.i
        HelloWorldService helloWorldService = new HelloWorldService();
923
924
925 42277 katerina.i
/*        System.out.println(helloWorldService.composePaging2(100, 0, 20));
926
        System.out.println(helloWorldService.composePaging2(100, 4, 20));
927 42275 katerina.i
928 42277 katerina.i
        System.out.println(helloWorldService.composePaging2(99, 4, 20));
929
        System.out.println(helloWorldService.composePaging2(99, 4, 20));
930
931
        System.out.println(helloWorldService.composePaging2(85, 4, 20));
932
933
         System.out.println(helloWorldService.composePaging2(0, 4, 20));
934
*/
935 45960 argiro.kok
/*
936 42277 katerina.i
         EmailValidator emailValidator = EmailValidator.getInstance();
937
         System.out.println(emailValidator.isValid("jate@gdddd"));
938
939
         InternetAddress emailAddr = null;
940
         try {
941
             emailAddr = new InternetAddress("jate@gdddd");
942
             emailAddr.validate();
943
         } catch (AddressException e) {
944
             System.out.println("false");
945
         }
946
         System.out.println("true");
947 45960 argiro.kok
*/
948 46789 sofia.balt
         ArrayList<String> insertedIds= new ArrayList<String>();
949 45960 argiro.kok
         insertedIds.add("1");
950
         insertedIds.add("2");
951
         insertedIds.add("3");
952
//         System.out.println(helloWorldService.compose204BulkInsertMessage(insertedIds,insertedIds));
953
954 42277 katerina.i
    }
955 45960 argiro.kok
956
957 46789 sofia.balt
}