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