577dbc98d36a7d42f6e459deb93826c69705e873
[aai/champ.git] / champ-service / src / main / java / org / onap / champ / ChampRESTAPI.java
1 /**
2  * ============LICENSE_START==========================================
3  * org.onap.aai
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 Amdocs
7  * ===================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22 package org.onap.champ;
23
24 import java.io.IOException;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Optional;
30 import java.util.Timer;
31
32 import javax.servlet.http.HttpServletRequest;
33 import javax.ws.rs.Consumes;
34 import javax.ws.rs.DELETE;
35 import javax.ws.rs.GET;
36 import javax.ws.rs.POST;
37 import javax.ws.rs.PUT;
38 import javax.ws.rs.Path;
39 import javax.ws.rs.PathParam;
40 import javax.ws.rs.Produces;
41 import javax.ws.rs.QueryParam;
42 import javax.ws.rs.core.Context;
43 import javax.ws.rs.core.HttpHeaders;
44 import javax.ws.rs.core.MediaType;
45 import javax.ws.rs.core.Response;
46 import javax.ws.rs.core.Response.Status;
47 import javax.ws.rs.core.UriInfo;
48
49 import org.json.JSONException;
50 import org.json.JSONObject;
51 import org.onap.aai.champcore.ChampTransaction;
52 import org.onap.aai.champcore.exceptions.ChampObjectNotExistsException;
53 import org.onap.aai.champcore.exceptions.ChampRelationshipNotExistsException;
54 import org.onap.aai.champcore.exceptions.ChampTransactionException;
55 import org.onap.aai.champcore.exceptions.ChampUnmarshallingException;
56 import org.onap.aai.champcore.model.ChampObject;
57 import org.onap.aai.champcore.model.ChampRelationship;
58 import org.onap.aai.cl.api.Logger;
59 import org.onap.aai.cl.eelf.LoggerFactory;
60 import org.onap.champ.async.ChampAsyncRequestProcessor;
61 import org.onap.champ.entity.ChampObjectDeserializer;
62 import org.onap.champ.entity.ChampObjectSerializer;
63 import org.onap.champ.entity.ChampRelationshipDeserializer;
64 import org.onap.champ.entity.ChampRelationshipSerializer;
65 import org.onap.champ.exception.ChampServiceException;
66 import org.onap.champ.service.ChampDataService;
67 import org.onap.champ.service.logging.ChampMsgs;
68 import org.onap.champ.service.logging.LoggingUtil;
69 import org.onap.champ.util.ChampProperties;
70 import org.onap.champ.util.ChampServiceConstants;
71
72 import com.fasterxml.jackson.core.JsonProcessingException;
73 import com.fasterxml.jackson.databind.ObjectMapper;
74 import com.fasterxml.jackson.databind.module.SimpleModule;
75
76 @Path(value = "/")
77 public class ChampRESTAPI {
78
79   private ObjectMapper mapper;
80
81   private ChampDataService champDataService;
82   private String TRANSACTION_METHOD = "method";
83   private Timer timer;
84
85   private Logger logger = LoggerFactory.getInstance().getLogger(ChampRESTAPI.class);
86   Logger auditLogger = LoggerFactory.getInstance().getAuditLogger(ChampRESTAPI.class.getName());
87   private static Logger metricsLogger = LoggerFactory.getInstance().getMetricsLogger(ChampRESTAPI.class.getName());
88
89   public ChampRESTAPI(ChampDataService champDataService, ChampAsyncRequestProcessor champAsyncRequestProcessor) {
90     this.champDataService = champDataService;
91
92     // Async request handling is optional.  
93     if (champAsyncRequestProcessor != null) {
94       timer = new Timer("ChampAsyncRequestProcessor-1");
95       timer.schedule(champAsyncRequestProcessor, champAsyncRequestProcessor.getRequestPollingTimeSeconds(),
96           champAsyncRequestProcessor.getRequestPollingTimeSeconds());
97     }
98
99     mapper = new ObjectMapper();
100     SimpleModule module = new SimpleModule();
101     module.addSerializer(ChampObject.class, new ChampObjectSerializer());
102     module.addDeserializer(ChampObject.class, new ChampObjectDeserializer());
103     module.addSerializer(ChampRelationship.class, new ChampRelationshipSerializer());
104     module.addDeserializer(ChampRelationship.class, new ChampRelationshipDeserializer());
105     mapper.registerModule(module);
106   }
107
108   @GET
109   @Path("echo")
110   @Produces(MediaType.TEXT_PLAIN)
111   public Response echo() {
112     return Response.ok().entity("alive").build();
113   }
114
115   @GET
116   @Path("objects/{objectId}")
117   @Produces(MediaType.APPLICATION_JSON)
118   public Response getObject(@PathParam("objectId") String objectId, @QueryParam("transactionId") String tId,
119       @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) {
120     LoggingUtil.initMdcContext(req, headers);
121     long startTimeInMs = System.currentTimeMillis();
122     logger.info(ChampMsgs.INCOMING_REQUEST, tId, objectId);
123
124     Response response = null;
125     ChampObject retrieved;
126
127     try {
128       ChampTransaction transaction = champDataService.getTransaction(tId);
129
130       if (tId != null && transaction == null) {
131         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
132       }
133       retrieved = champDataService.getObject(objectId, Optional.ofNullable(transaction));
134       if (retrieved == null) {
135         response = Response.status(Status.NOT_FOUND).entity(objectId + " not found").build();
136       } else {
137         response = Response.status(Status.OK).entity(mapper.writeValueAsString(retrieved)).build();
138       }
139
140     } catch (JsonProcessingException e) {
141       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
142     } catch (ChampServiceException ce) {
143       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
144     } finally {
145       logger.debug(response.getEntity().toString());
146       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
147       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
148     }
149
150     return response;
151   }
152
153   @DELETE
154   @Path("objects/{objectId}")
155   public Response deleteObject(@PathParam("objectId") String objectId, @QueryParam("transactionId") String tId,
156       @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) {
157     LoggingUtil.initMdcContext(req, headers);
158     long startTimeInMs = System.currentTimeMillis();
159     logger.info(ChampMsgs.INCOMING_REQUEST, tId, objectId);
160     ChampObject retrieved;
161     Response response = null;
162     try {
163       ChampTransaction transaction = champDataService.getTransaction(tId);
164
165       if (tId != null && transaction == null) {
166         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
167       }
168       champDataService.deleteObject(objectId, Optional.ofNullable(transaction));
169
170       response = Response.status(Status.OK).build();
171     } catch (ChampObjectNotExistsException e) {
172       response = Response.status(Status.NOT_FOUND).entity(objectId + " not found").build();
173     } catch (ChampServiceException ce) {
174       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
175     } catch (ChampTransactionException | ChampUnmarshallingException e) {
176       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
177     } finally {
178       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
179       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "DELETE",
180           Long.toString(System.currentTimeMillis() - startTimeInMs));
181     }
182     return response;
183   }
184
185   @POST
186   @Path("objects")
187   @Consumes(MediaType.APPLICATION_JSON)
188   @Produces(MediaType.APPLICATION_JSON)
189   public Response postObject(String champObj, @QueryParam("transactionId") String tId, @Context HttpHeaders headers,
190       @Context UriInfo uriInfo, @Context HttpServletRequest req) {
191     LoggingUtil.initMdcContext(req, headers);
192     long startTimeInMs = System.currentTimeMillis();
193     logger.info(ChampMsgs.INCOMING_REQUEST, tId, champObj);
194     Response response = null;
195     try {
196       ChampTransaction transaction = champDataService.getTransaction(tId);
197       if (tId != null && transaction == null) {
198         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
199       }
200       ChampObject champObject = mapper.readValue(champObj, ChampObject.class);
201
202       ChampObject created = champDataService.storeObject(champObject, Optional.ofNullable(transaction));
203       response = Response.status(Status.CREATED).entity(mapper.writeValueAsString(created)).build();
204     } catch (IOException e) {
205       response = Response.status(Status.BAD_REQUEST).entity("Unable to parse the payload").build();
206     } catch (ChampServiceException ce) {
207       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
208     } catch (IllegalArgumentException e) {
209       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
210     } catch (Exception e) {
211       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
212       LoggingUtil.logInternalError(logger, e);
213     } finally {
214       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
215       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "POST",
216           Long.toString(System.currentTimeMillis() - startTimeInMs));
217     }
218     return response;
219   }
220
221   @PUT
222   @Path("objects/{objectId}")
223   @Consumes(MediaType.APPLICATION_JSON)
224   @Produces(MediaType.APPLICATION_JSON)
225   public Response putObject(@PathParam("objectId") String objectId, String champObj,
226       @QueryParam("transactionId") String tId, @Context HttpHeaders headers, @Context UriInfo uriInfo,
227       @Context HttpServletRequest req) {
228     LoggingUtil.initMdcContext(req, headers);
229     long startTimeInMs = System.currentTimeMillis();
230     logger.info(ChampMsgs.INCOMING_REQUEST, tId, objectId + " " + champObj);
231
232     Response response = null;
233     try {
234       ChampTransaction transaction = champDataService.getTransaction(tId);
235       if (tId != null && transaction == null) {
236         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
237       }
238
239       ChampObject co = mapper.readValue(champObj, ChampObject.class);
240       // check if key is present or if it equals the key that is in the URI
241       ChampObject updated = champDataService.replaceObject(co, objectId, Optional.ofNullable(transaction));
242
243       response = Response.status(Status.OK).entity(mapper.writeValueAsString(updated)).build();
244     } catch (IOException e) {
245       response = Response.status(Status.BAD_REQUEST).entity("Unable to parse the payload").build();
246     } catch (ChampServiceException ce) {
247       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
248     } catch (IllegalArgumentException e) {
249       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
250     } catch (Exception e) {
251       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
252       LoggingUtil.logInternalError(logger, e);
253     } finally {
254       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
255       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "PUT", Long.toString(System.currentTimeMillis() - startTimeInMs));
256     }
257     return response;
258   }
259
260   @GET
261   @Path("objects/relationships/{oId}")
262   @Produces(MediaType.APPLICATION_JSON)
263   public Response getEdges(@PathParam("oId") String oId, @QueryParam("transactionId") String tId,
264       @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) {
265     LoggingUtil.initMdcContext(req, headers);
266     long startTimeInMs = System.currentTimeMillis();
267     List<ChampRelationship> retrieved;
268     Optional<ChampObject> rObject;
269     Response response = null;
270     ChampTransaction transaction = null;
271     try {
272
273       retrieved = champDataService.getRelationshipsByObject(oId, Optional.ofNullable(transaction));
274       response = Response.status(Status.OK).entity(mapper.writeValueAsString(retrieved)).build();
275     } catch (JsonProcessingException e) {
276       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
277     } catch (ChampServiceException ce) {
278       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
279     } catch (Exception e) {
280       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
281       LoggingUtil.logInternalError(logger, e);
282     } finally {
283       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
284       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
285     }
286     return response;
287   }
288
289   @GET
290   @Path("objects/filter/")
291   @Produces(MediaType.APPLICATION_JSON)
292   public Response filterObject(@Context HttpHeaders headers, @Context UriInfo uriInfo,
293       @Context HttpServletRequest req) {
294     LoggingUtil.initMdcContext(req, headers);
295     long startTimeInMs = System.currentTimeMillis();
296     String propertiesKey = ChampProperties.get(ChampServiceConstants.CHAMP_COLLECTION_PROPERTIES_KEY);
297     List<ChampObject> objects;
298     Map<String, Object> filter = new HashMap<>();
299
300     for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
301       if (!e.getKey().equals(propertiesKey)) {
302         filter.put(e.getKey(), e.getValue().get(0));
303       }
304     }
305
306     HashSet<String> properties;
307     if (uriInfo.getQueryParameters().containsKey(propertiesKey)) {
308       properties = new HashSet<>(uriInfo.getQueryParameters().get(propertiesKey));
309     } else {
310       properties = new HashSet<>();
311     }
312
313     Response response = null;
314     try {
315       objects = champDataService.queryObjects(filter, properties);
316       response = Response.status(Status.OK).type(MediaType.APPLICATION_JSON).entity(mapper.writeValueAsString(objects))
317           .build();
318     } catch (JsonProcessingException e) {
319       e.printStackTrace();
320       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
321     } catch (ChampServiceException e1) {
322       response = Response.status(e1.getHttpStatus()).entity(e1.getMessage()).build();
323     } catch (Exception e) {
324       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
325       LoggingUtil.logInternalError(logger, e);
326     } finally {
327       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
328       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
329     }
330     return response;
331   }
332
333   @GET
334   @Path("relationships/{rId}")
335   @Produces(MediaType.APPLICATION_JSON)
336   public Response getRelationship(@PathParam("rId") String rId, @QueryParam("transactionId") String tId,
337       @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) {
338     LoggingUtil.initMdcContext(req, headers);
339     long startTimeInMs = System.currentTimeMillis();
340     logger.info(ChampMsgs.INCOMING_REQUEST, tId, rId);
341     ChampRelationship retrieved;
342     Response response = null;
343     try {
344       ChampTransaction transaction = champDataService.getTransaction(tId);
345
346       if (tId != null && transaction == null) {
347         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
348       }
349       retrieved = champDataService.getRelationship(rId, Optional.ofNullable(transaction));
350       if (retrieved == null) {
351         response = Response.status(Status.NOT_FOUND).entity(rId + " not found").build();
352         return response;
353       }
354       response = Response.status(Status.OK).entity(mapper.writeValueAsString(retrieved)).build();
355
356     } catch (IOException e) {
357       response = Response.status(Status.BAD_REQUEST).entity("Unable to parse the payload").build();
358     } catch (ChampServiceException ce) {
359       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
360     } catch (Exception e) {
361       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
362       LoggingUtil.logInternalError(logger, e);
363     } finally {
364       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
365       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
366     }
367     return response;
368   }
369
370   @POST
371   @Path("relationships")
372   @Consumes(MediaType.APPLICATION_JSON)
373   @Produces(MediaType.APPLICATION_JSON)
374   public Response postRelationships(String relationship, @QueryParam("transactionId") String tId,
375       @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) {
376     LoggingUtil.initMdcContext(req, headers);
377     long startTimeInMs = System.currentTimeMillis();
378     logger.info(ChampMsgs.INCOMING_REQUEST, tId, relationship);
379     Response response = null;
380     try {
381       ChampTransaction transaction = champDataService.getTransaction(tId);
382       if (tId != null && transaction == null) {
383         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
384       }
385       ChampRelationship r = mapper.readValue(relationship, ChampRelationship.class);
386
387       ChampRelationship created = champDataService.storeRelationship(r, Optional.ofNullable(transaction));
388
389       response = Response.status(Status.CREATED).entity(mapper.writeValueAsString(created)).build();
390     } catch (IOException e) {
391       response = Response.status(Status.BAD_REQUEST).entity("Unable to parse the payload").build();
392     } catch (ChampServiceException ce) {
393       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
394     } catch (IllegalArgumentException e) {
395       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
396     } catch (Exception e) {
397       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
398       LoggingUtil.logInternalError(logger, e);
399     } finally {
400       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
401       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "POST",
402           Long.toString(System.currentTimeMillis() - startTimeInMs));
403     }
404     return response;
405   }
406
407   @PUT
408   @Path("relationships/{rId}")
409   @Consumes(MediaType.APPLICATION_JSON)
410   @Produces(MediaType.APPLICATION_JSON)
411   public Response updateRelationship(@PathParam("rId") String rId, String relationship,
412       @QueryParam("transactionId") String tId, @Context HttpHeaders headers, @Context UriInfo uriInfo,
413       @Context HttpServletRequest req) {
414     LoggingUtil.initMdcContext(req, headers);
415     long startTimeInMs = System.currentTimeMillis();
416     logger.info(ChampMsgs.INCOMING_REQUEST, tId, relationship);
417
418     Response response = null;
419     try {
420       ChampTransaction transaction = champDataService.getTransaction(tId);
421       if (tId != null && transaction == null) {
422         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
423       }
424       ChampRelationship r = mapper.readValue(relationship, ChampRelationship.class);
425       ChampRelationship updated = champDataService.updateRelationship(r, rId, Optional.ofNullable(transaction));
426
427       response = Response.status(Status.OK).entity(mapper.writeValueAsString(updated)).build();
428     } catch (IOException e) {
429       response = Response.status(Status.BAD_REQUEST).entity("Unable to parse the payload").build();
430     } catch (ChampServiceException ce) {
431       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
432     } catch (IllegalArgumentException e) {
433       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
434     } catch (Exception e) {
435       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
436       LoggingUtil.logInternalError(logger, e);
437     } finally {
438       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
439       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "PUT", Long.toString(System.currentTimeMillis() - startTimeInMs));
440     }
441     return response;
442   }
443
444   @DELETE
445   @Path("relationships/{relationshipId}")
446   public Response deleteRelationship(@PathParam("relationshipId") String relationshipId,
447       @QueryParam("transactionId") String tId, @Context HttpHeaders headers, @Context UriInfo uriInfo,
448       @Context HttpServletRequest req) {
449     LoggingUtil.initMdcContext(req, headers);
450     long startTimeInMs = System.currentTimeMillis();
451     logger.info(ChampMsgs.INCOMING_REQUEST, tId, relationshipId);
452
453     Response response = null;
454     try {
455       ChampTransaction transaction = champDataService.getTransaction(tId);
456       if (tId != null && transaction == null) {
457         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
458       }
459       champDataService.deleteRelationship(relationshipId, Optional.ofNullable(transaction));
460       response = Response.status(Status.OK).build();
461
462     } catch (ChampRelationshipNotExistsException e) {
463       response = Response.status(Status.NOT_FOUND).entity(relationshipId + " not found").build();
464     } catch (ChampServiceException ce) {
465       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
466     } catch (ChampTransactionException | ChampUnmarshallingException e) {
467       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
468     } finally {
469       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
470       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "DELETE",
471           Long.toString(System.currentTimeMillis() - startTimeInMs));
472     }
473     return response;
474   }
475
476   @GET
477   @Path("relationships/filter/")
478   @Produces(MediaType.APPLICATION_JSON)
479   public Response filterMethod(@Context HttpHeaders headers, @Context UriInfo uriInfo,
480       @Context HttpServletRequest req) {
481     LoggingUtil.initMdcContext(req, headers);
482     long startTimeInMs = System.currentTimeMillis();
483     List<ChampRelationship> list;
484     Map<String, Object> filter = new HashMap<>();
485     for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
486       filter.put(e.getKey(), e.getValue().get(0));
487     }
488     Response response = null;
489     try {
490       list = champDataService.queryRelationships(filter);
491       response = Response.status(Status.OK).type(MediaType.APPLICATION_JSON).entity(mapper.writeValueAsString(list))
492           .build();
493     } catch (JsonProcessingException e) {
494       e.printStackTrace();
495       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
496     } catch (ChampServiceException e1) {
497       response = Response.status(e1.getHttpStatus()).entity(e1.getMessage()).build();
498     } catch (Exception e) {
499       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
500       LoggingUtil.logInternalError(logger, e);
501     } finally {
502       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
503       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
504     }
505     return response;
506   }
507
508   @POST
509   @Path("transaction")
510   @Produces(MediaType.TEXT_PLAIN)
511   public Response openTransaction(@Context HttpHeaders headers, @Context UriInfo uriInfo,
512       @Context HttpServletRequest req) {
513     LoggingUtil.initMdcContext(req, headers);
514     long startTimeInMs = System.currentTimeMillis();
515     Status s;
516     String transaction = champDataService.openTransaction();
517
518     s = Status.OK;
519     Response response = Response.status(s).entity(transaction).build();
520     logger.info(ChampMsgs.PROCESS_EVENT, "Opened Transaction with ID: " + transaction, s.toString());
521     LoggingUtil.logRestRequest(logger, auditLogger, req, response);
522     metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "POST", Long.toString(System.currentTimeMillis() - startTimeInMs));
523     return response;
524   }
525
526   @GET
527   @Path("transaction/{tId}")
528   public Response getSpecificTransaction(@PathParam("tId") String tId, @Context HttpHeaders headers,
529       @Context UriInfo uriInfo, @Context HttpServletRequest req) {
530     LoggingUtil.initMdcContext(req, headers);
531     long startTimeInMs = System.currentTimeMillis();
532
533     Response response = null;
534     ChampTransaction transaction = champDataService.getTransaction(tId);
535     if (transaction == null) {
536       response = Response.status(Status.NOT_FOUND).entity("transaction " + tId + " not found").build();
537       return response;
538     }
539
540     try {
541       response = Response.status(Status.OK).entity(mapper.writeValueAsString(tId + " is OPEN")).build();
542     } catch (JsonProcessingException e) {
543       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
544     } catch (Exception e) {
545       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
546       LoggingUtil.logInternalError(logger, e);
547     } finally {
548       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
549       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
550     }
551     return response;
552   }
553
554   @PUT
555   @Path("transaction/{tId}")
556   @Produces(MediaType.TEXT_PLAIN)
557   @Consumes(MediaType.APPLICATION_JSON)
558   public Response updateTransaction(String t, @PathParam("tId") String tId, @Context HttpHeaders headers,
559       @Context UriInfo uriInfo, @Context HttpServletRequest req) {
560     LoggingUtil.initMdcContext(req, headers);
561     long startTimeInMs = System.currentTimeMillis();
562     logger.info(ChampMsgs.INCOMING_REQUEST, tId, "COMMIT/ROLLBACK");
563
564     Response response = null;
565     try {
566       JSONObject jsonObj = new JSONObject(t);
567       String method = jsonObj.getString(this.TRANSACTION_METHOD);
568
569       if (method.equals("commit")) {
570         champDataService.commitTransaction(tId);
571         response = Response.status(Status.OK).entity("COMMITTED").build();
572
573       } else if (method.equals("rollback")) {
574         champDataService.rollbackTransaction(tId);
575         response = Response.status(Status.OK).entity("ROLLED BACK").build();
576       } else {
577         response = Response.status(Status.BAD_REQUEST).entity("Invalid Method: " + method).build();
578         return response;
579       }
580
581     } catch (ChampTransactionException e) {
582       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
583     } catch (JSONException e) {
584       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
585     } catch (ChampServiceException e) {
586       response = Response.status(e.getHttpStatus()).entity(e.getMessage()).build();
587     } catch (Exception e) {
588       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
589       LoggingUtil.logInternalError(logger, e);
590     } finally {
591       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
592       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "PUT", Long.toString(System.currentTimeMillis() - startTimeInMs));
593     }
594     return response;
595   }
596
597 }