Project

General

Profile

« Previous | Next » 

Revision 42275

First version of REST API for connector - get claims per project available

View differences:

modules/uoa-openaire-connector/branches/newClaimAPI/src/main/java/eu/dnetlib/openaire/rest/HelloWorldService.java
1
package eu.dnetlib.openaire.rest;
2

  
3
import com.google.gson.Gson;
4
import eu.dnetlib.data.claims.migration.entity.Claim;
5
import eu.dnetlib.data.claims.migration.handler.ClaimHandler;
6
import eu.dnetlib.data.claims.migration.handler.FetchClaimHandler;
7
import org.apache.log4j.Logger;
8
import org.springframework.beans.factory.annotation.Autowired;
9
import org.springframework.stereotype.Component;
10

  
11
import javax.servlet.http.HttpServletRequest;
12
import javax.ws.rs.*;
13
import javax.ws.rs.core.Context;
14
import javax.ws.rs.core.MediaType;
15
import javax.ws.rs.core.Response;
16
import java.util.List;
17

  
18
/**
19
 * Created by kiatrop on 15/4/2016.
20
 */
21
@Component
22
@Path("/claimsService")
23
public class HelloWorldService {
24

  
25
    Logger logger = Logger.getLogger(HelloWorldService.class);
26

  
27
    @Autowired
28
    private FetchClaimHandler fetchClaimHandler = null;
29

  
30
    @Autowired
31
    private ClaimHandler claimHandler = null;
32

  
33
    @GET
34
    @Path("projects/{projectId}/claims")
35
    public Response getMsg(@PathParam("projectId") String projectId,
36
                           @DefaultValue("0") @QueryParam("offset") int offset,
37
                           @DefaultValue("20") @QueryParam("limit") int limit,
38
                           @Context HttpServletRequest request) {
39

  
40
        int total = -1;
41

  
42
        if (projectId == null || projectId.isEmpty()) {
43
            return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Project id cannot be empty."))
44
                    .type(MediaType.APPLICATION_JSON).build();
45
        }
46

  
47
        List<Claim> claims = null;
48

  
49
        try {
50
            claims = fetchClaimHandler.fetchClaimsByProject(projectId, limit, offset);
51
            total = fetchClaimHandler.countClaimsByProject(projectId);
52

  
53
        } catch (Exception e) {
54
            logger.error("Could not fetch claims for project with id " + projectId);
55
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
56
                    " for projects with id " + projectId + ".", e)).type(MediaType.APPLICATION_JSON).build();
57
        }
58
        
59
        return Response.status(200).entity(composeDataResponse(request, claims, total, offset, limit)).build();
60
    }
61

  
62
    /*
63
    @GET
64
    @Path("/contexts/{contextId}/claims")
65
    public Response getContextClaims(@PathParam("projectId") String contextId,
66
                           @DefaultValue("0") @QueryParam("offset") int offset,
67
                           @DefaultValue("20") @QueryParam("limit") int limit) {
68

  
69
        if (contextId == null || contextId.isEmpty()) {
70
            return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
71
                    .type(MediaType.APPLICATION_JSON).build();
72
        }
73

  
74
        List<Claim> claims = null;
75

  
76
        try {
77
            claims = fetchClaimHandler.fetchClaimsByContext(contextId, limit, offset);
78

  
79
        } catch (Exception e) {
80
            logger.error("Could not fetch claims for context with id " + contextId);
81
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
82
                    " for context with id " + contextId + ".", e)).type(MediaType.APPLICATION_JSON).build();
83
        }
84

  
85
        return Response.status(200).entity(new Gson().toJson(claims)).build();
86
    }
87

  
88
    @GET
89
    @Path("/results/{resultId}/claims")
90
    public Response getResultClaims(@PathParam("resultId") String resultId,
91
                                     @DefaultValue("0") @QueryParam("offset") int offset,
92
                                     @DefaultValue("20") @QueryParam("limit") int limit) {
93

  
94
        if (resultId == null || resultId.isEmpty()) {
95
            return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("Context id cannot be empty."))
96
                    .type(MediaType.APPLICATION_JSON).build();
97
        }
98

  
99
        List<Claim> claims = null;
100

  
101
        try {
102
            claims = fetchClaimHandler.fetchClaimsByContext(resultId, limit, offset);
103

  
104
        } catch (Exception e) {
105
            logger.error("Could not fetch claims for result with id " + resultId);
106
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
107
                    " for result with id " + resultId + ".", e)).type(MediaType.APPLICATION_JSON).build();
108
        }
109

  
110
        return Response.status(200).entity(new Gson().toJson(claims)).build();
111
    }
112

  
113

  
114
    @GET
115
    @Path("/results/{userMail}/claims")
116
    public Response getUserClaims(@PathParam("userMail") String userMail,
117
                                    @DefaultValue("0") @QueryParam("offset") int offset,
118
                                    @DefaultValue("20") @QueryParam("limit") int limit) {
119

  
120
        if (userMail == null || userMail.isEmpty()) {
121
            return Response.status(Response.Status.BAD_REQUEST).entity(compose400Message("User e-mail cannot be empty."))
122
                    .type(MediaType.APPLICATION_JSON).build();
123
        }
124

  
125
        List<Claim> claims = null;
126

  
127
        try {
128
            claims = fetchClaimHandler.fetchClaimsByUser(userMail, limit, offset);
129

  
130
        } catch (Exception e) {
131
            logger.error("Could not fetch claims for result with id " + userMail);
132
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims" +
133
                    " for user with e-mail " + userMail + ".", e)).type(MediaType.APPLICATION_JSON).build();
134
        }
135

  
136
        return Response.status(200).entity(new Gson().toJson(claims)).build();
137
    }
138

  
139

  
140

  
141
    @GET
142
    @Path("/claims/{claimId}")
143
    public Response getClaimsById(@PathParam("claimId") String claimId,
144
                                  @DefaultValue("0") @QueryParam("offset") int offset,
145
                                  @DefaultValue("20") @QueryParam("limit") int limit) {
146

  
147
        List<Claim> claims = null;
148

  
149
        if (claimId == null || claimId.isEmpty()) {
150
            try {
151
                claims = fetchClaimHandler.fetchAllClaims(limit, offset);
152
                return Response.status(200).entity(new Gson().toJson(claims)).build();
153

  
154
            } catch (Exception e) {
155
                logger.error("Could not fetch claims.");
156
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to fetch claims.", e))
157
                        .type(MediaType.APPLICATION_JSON).build();
158
            }
159
        }
160

  
161
        claims = new ArrayList<Claim>();
162
        Claim claim =  null;
163

  
164
        if(claim != null) {
165
            claims.add(claim);
166
        }
167
        return Response.status(200).entity(new Gson().toJson(claims)).build();
168
    }
169

  
170

  
171
    @DELETE
172
    @Path("/claims/{claimId}")
173
    public Response deleteClaim(@PathParam("claimId") String claimId) {
174

  
175
        if (claimId == null || claimId.isEmpty()) {
176
            return Response.status(Response.Status.NOT_FOUND).entity(compose404Message("Claim id cannot be empty."))
177
                    .type(MediaType.APPLICATION_JSON).build();
178
        }
179

  
180
        try {
181
            claimHandler.deleteClaim(claimId);
182

  
183
        } catch (Exception e) {
184
            logger.error("Fail to delete claim with id " + claimId + ".", e);
185
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to delete claim with id " + claimId +".", e))
186
                    .type(MediaType.APPLICATION_JSON).build();
187
        }
188

  
189
        return Response.status(200).entity(compose200Message()).type(MediaType.APPLICATION_JSON).build();
190
    }
191

  
192

  
193
    @POST
194
    @Path("/addClaim")
195
    @Produces(MediaType.APPLICATION_JSON)
196
    @Consumes(MediaType.APPLICATION_JSON)
197
    public Response addClaim(String input, @Context HttpServletRequest request) {
198
        JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
199

  
200
        String claimedBy = jsonObject.get("claimedBy").getAsString();
201
        String sourceId = jsonObject.get("sourceId").getAsString();
202
        String sourceType = jsonObject.get("sourceType").getAsString();
203
        String sourceCollectedFrom = jsonObject.get("sourceCollectedFrom").getAsString();
204

  
205
        String targetId = jsonObject.get("targetId").getAsString();
206
        String targetType = jsonObject.get("targetType").getAsString();
207
        String targetCollectedFrom = jsonObject.get("targetCollectedFrom").getAsString();
208

  
209
        try {
210
            claimHandler.buildAndInsertClaim(claimedBy, sourceType, sourceId, sourceCollectedFrom, targetType, targetId, targetCollectedFrom);
211

  
212
        } catch (Exception e) {
213
            logger.error("Fail to add new claim.", e);
214
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(compose500Message("Fail to add new claim.", e))
215
                    .type(MediaType.APPLICATION_JSON).build();
216
        }
217

  
218
        return Response.status(200).entity(compose200PostMessage(request, "id")).type(MediaType.APPLICATION_JSON).build();
219

  
220
    }
221
*/
222
    @Path("/katerinaki")
223
    @GET
224
    @Produces(MediaType.APPLICATION_JSON)
225
    public Response fetchClaims() {
226

  
227
        try {
228

  
229
            String json = "{allakse pali}";
230
            return  Response.ok(json, MediaType.APPLICATION_JSON).build();
231

  
232
        } catch (Exception e) {
233
            e.printStackTrace();
234
        }
235
        return null;
236
    }
237

  
238
    private String compose400Message(String message) {
239
        return  "{ \"status\" : \"error\", \"code\" : \"400\", \"message\" : \"  " + message +" \" }";
240
    }
241

  
242
    private String compose404Message(String message) {
243
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
244
    }
245

  
246
    private String compose500Message(String message, Exception exception) {
247
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
248
                "\"description\" : \""+  exception.getMessage() +"\" }";
249
    }
250

  
251
    private  String compose200Message(){
252
        return " { \"status\" : \"success\", \"code\": \"200\" }";
253
    }
254

  
255
    private  String compose200PostMessage(@Context HttpServletRequest request, String claimId){
256
        String url = request.getRequestURL().toString();
257
        String query = request.getQueryString();
258
        String reqString = url + " + " + query;
259

  
260
        return " { \"status\" : \"success\", \"code\": \"200\", \"link\": " + url + query + "\\claims\\" + claimId +" }";
261
    }
262

  
263
    private String composeDataResponse(HttpServletRequest request, List<Claim> claims, int total, int offset, int limit) {
264
        return " { \"status\" : \"success\", \"code\": \"200\", " + composePaging(request, total, offset, limit) + ", "
265
                + "\"data\" : " + new Gson().toJson(claims) + " }";
266
    }
267

  
268
    private String composePaging(HttpServletRequest request, int total, int currentOffset, int limit) {
269
        String url = request.getRequestURL().toString();
270
        String query = request.getQueryString();
271

  
272
        String first = url+query+"?offset=0&limit=20";
273

  
274
        int previousPage;
275
        int nextPage;
276
        int lastPage;
277

  
278
        if (total < currentOffset) {
279
            lastPage = 0;
280
        } else {
281
            if(total%limit == 0) {
282
                lastPage = total/limit-1;
283
            } else {
284
                lastPage = total/limit ;
285
            }
286
        }
287
        String last = url+query+"?offset=" + lastPage + "&limit=20";
288

  
289
        if (currentOffset-1 < 0) {
290
            previousPage = 0;
291
        } else {
292
            previousPage = currentOffset-1;
293
        }
294
        String previous = url+query+"?offset=" + previousPage + "&limit=20";
295

  
296
        if (currentOffset+1 > lastPage) {
297
            nextPage = lastPage;
298

  
299
        } else {
300
            nextPage = currentOffset + 1;
301
        }
302
        String next = url+query+"?offset=" + nextPage + "&limit=20";
303

  
304
        return "\"paging\": [" +  "{\"rel\":\"first\", \"href\":\"" + first +"\"}, {\"rel\":\"last\", \"href\":\"" + last + "\"}, {\"rel\":\"previous\", \"href\": \"" + previous + "\"}, {\"rel\":\"next\", \"href\":\"" +  next +"\"}"+ "]";
305
    }
306

  
307

  
308
   /* public static void main(String[] args) {
309
        HelloWorldService helloWorldService = new HelloWorldService();
310

  
311
        System.out.println(helloWorldService.composePaging(100, 0, 20, 0));
312
        System.out.println(helloWorldService.composePaging(100, 4, 20, 4));
313

  
314
        System.out.println(helloWorldService.composePaging(99, 4, 20, 0));
315
        System.out.println(helloWorldService.composePaging(99, 4, 20, 4));
316

  
317
        System.out.println(helloWorldService.composePaging(85, 4, 20, 4));
318
    }*/
319
}

Also available in: Unified diff