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