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