Update license date and text
[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 (Exception e) {
208       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
209       LoggingUtil.logInternalError(logger, e);
210     } finally {
211       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
212       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "POST",
213           Long.toString(System.currentTimeMillis() - startTimeInMs));
214     }
215     return response;
216   }
217
218   @PUT
219   @Path("objects/{objectId}")
220   @Consumes(MediaType.APPLICATION_JSON)
221   @Produces(MediaType.APPLICATION_JSON)
222   public Response putObject(@PathParam("objectId") String objectId, String champObj,
223       @QueryParam("transactionId") String tId, @Context HttpHeaders headers, @Context UriInfo uriInfo,
224       @Context HttpServletRequest req) {
225     LoggingUtil.initMdcContext(req, headers);
226     long startTimeInMs = System.currentTimeMillis();
227     logger.info(ChampMsgs.INCOMING_REQUEST, tId, objectId + " " + champObj);
228
229     Response response = null;
230     try {
231       ChampTransaction transaction = champDataService.getTransaction(tId);
232       if (tId != null && transaction == null) {
233         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
234       }
235
236       ChampObject co = mapper.readValue(champObj, ChampObject.class);
237       // check if key is present or if it equals the key that is in the URI
238       ChampObject updated = champDataService.replaceObject(co, objectId, Optional.ofNullable(transaction));
239
240       response = Response.status(Status.OK).entity(mapper.writeValueAsString(updated)).build();
241     } catch (IOException e) {
242       response = Response.status(Status.BAD_REQUEST).entity("Unable to parse the payload").build();
243     } catch (ChampServiceException ce) {
244       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
245     } catch (Exception e) {
246       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
247       LoggingUtil.logInternalError(logger, e);
248     } finally {
249       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
250       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "PUT", Long.toString(System.currentTimeMillis() - startTimeInMs));
251     }
252     return response;
253   }
254
255   @GET
256   @Path("objects/relationships/{oId}")
257   @Produces(MediaType.APPLICATION_JSON)
258   public Response getEdges(@PathParam("oId") String oId, @QueryParam("transactionId") String tId,
259       @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) {
260     LoggingUtil.initMdcContext(req, headers);
261     long startTimeInMs = System.currentTimeMillis();
262     List<ChampRelationship> retrieved;
263     Optional<ChampObject> rObject;
264     Response response = null;
265     ChampTransaction transaction = null;
266     try {
267
268       retrieved = champDataService.getRelationshipsByObject(oId, Optional.ofNullable(transaction));
269       response = Response.status(Status.OK).entity(mapper.writeValueAsString(retrieved)).build();
270     } catch (JsonProcessingException e) {
271       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
272     } catch (ChampServiceException ce) {
273       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
274     } catch (Exception e) {
275       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
276       LoggingUtil.logInternalError(logger, e);
277     } finally {
278       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
279       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
280     }
281     return response;
282   }
283
284   @GET
285   @Path("objects/filter/")
286   @Produces(MediaType.APPLICATION_JSON)
287   public Response filterObject(@Context HttpHeaders headers, @Context UriInfo uriInfo,
288       @Context HttpServletRequest req) {
289     LoggingUtil.initMdcContext(req, headers);
290     long startTimeInMs = System.currentTimeMillis();
291     String propertiesKey = ChampProperties.get(ChampServiceConstants.CHAMP_COLLECTION_PROPERTIES_KEY);
292     List<ChampObject> objects;
293     Map<String, Object> filter = new HashMap<>();
294
295     for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
296       if (!e.getKey().equals(propertiesKey)) {
297         filter.put(e.getKey(), e.getValue().get(0));
298       }
299     }
300
301     HashSet<String> properties;
302     if (uriInfo.getQueryParameters().containsKey(propertiesKey)) {
303       properties = new HashSet<>(uriInfo.getQueryParameters().get(propertiesKey));
304     } else {
305       properties = new HashSet<>();
306     }
307
308     Response response = null;
309     try {
310       objects = champDataService.queryObjects(filter, properties);
311       response = Response.status(Status.OK).type(MediaType.APPLICATION_JSON).entity(mapper.writeValueAsString(objects))
312           .build();
313     } catch (JsonProcessingException e) {
314       e.printStackTrace();
315       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
316     } catch (ChampServiceException e1) {
317       response = Response.status(e1.getHttpStatus()).entity(e1.getMessage()).build();
318     } catch (Exception e) {
319       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
320       LoggingUtil.logInternalError(logger, e);
321     } finally {
322       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
323       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
324     }
325     return response;
326   }
327
328   @GET
329   @Path("relationships/{rId}")
330   @Produces(MediaType.APPLICATION_JSON)
331   public Response getRelationship(@PathParam("rId") String rId, @QueryParam("transactionId") String tId,
332       @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) {
333     LoggingUtil.initMdcContext(req, headers);
334     long startTimeInMs = System.currentTimeMillis();
335     logger.info(ChampMsgs.INCOMING_REQUEST, tId, rId);
336     ChampRelationship retrieved;
337     Response response = null;
338     try {
339       ChampTransaction transaction = champDataService.getTransaction(tId);
340
341       if (tId != null && transaction == null) {
342         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
343       }
344       retrieved = champDataService.getRelationship(rId, Optional.ofNullable(transaction));
345       if (retrieved == null) {
346         response = Response.status(Status.NOT_FOUND).entity(rId + " not found").build();
347         return response;
348       }
349       response = Response.status(Status.OK).entity(mapper.writeValueAsString(retrieved)).build();
350
351     } catch (IOException e) {
352       response = Response.status(Status.BAD_REQUEST).entity("Unable to parse the payload").build();
353     } catch (ChampServiceException ce) {
354       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
355     } catch (Exception e) {
356       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
357       LoggingUtil.logInternalError(logger, e);
358     } finally {
359       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
360       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
361     }
362     return response;
363   }
364
365   @POST
366   @Path("relationships")
367   @Consumes(MediaType.APPLICATION_JSON)
368   @Produces(MediaType.APPLICATION_JSON)
369   public Response postRelationships(String relationship, @QueryParam("transactionId") String tId,
370       @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context HttpServletRequest req) {
371     LoggingUtil.initMdcContext(req, headers);
372     long startTimeInMs = System.currentTimeMillis();
373     logger.info(ChampMsgs.INCOMING_REQUEST, tId, relationship);
374     Response response = null;
375     try {
376       ChampTransaction transaction = champDataService.getTransaction(tId);
377       if (tId != null && transaction == null) {
378         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
379       }
380       ChampRelationship r = mapper.readValue(relationship, ChampRelationship.class);
381
382       ChampRelationship created = champDataService.storeRelationship(r, Optional.ofNullable(transaction));
383
384       response = Response.status(Status.CREATED).entity(mapper.writeValueAsString(created)).build();
385     } catch (IOException e) {
386       response = Response.status(Status.BAD_REQUEST).entity("Unable to parse the payload").build();
387     } catch (ChampServiceException ce) {
388       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
389     } catch (Exception e) {
390       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
391       LoggingUtil.logInternalError(logger, e);
392     } finally {
393       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
394       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "POST",
395           Long.toString(System.currentTimeMillis() - startTimeInMs));
396     }
397     return response;
398   }
399
400   @PUT
401   @Path("relationships/{rId}")
402   @Consumes(MediaType.APPLICATION_JSON)
403   @Produces(MediaType.APPLICATION_JSON)
404   public Response updateRelationship(@PathParam("rId") String rId, String relationship,
405       @QueryParam("transactionId") String tId, @Context HttpHeaders headers, @Context UriInfo uriInfo,
406       @Context HttpServletRequest req) {
407     LoggingUtil.initMdcContext(req, headers);
408     long startTimeInMs = System.currentTimeMillis();
409     logger.info(ChampMsgs.INCOMING_REQUEST, tId, relationship);
410
411     Response response = null;
412     try {
413       ChampTransaction transaction = champDataService.getTransaction(tId);
414       if (tId != null && transaction == null) {
415         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
416       }
417       ChampRelationship r = mapper.readValue(relationship, ChampRelationship.class);
418       ChampRelationship updated = champDataService.updateRelationship(r, rId, Optional.ofNullable(transaction));
419
420       response = Response.status(Status.OK).entity(mapper.writeValueAsString(updated)).build();
421     } catch (IOException e) {
422       response = Response.status(Status.BAD_REQUEST).entity("Unable to parse the payload").build();
423     } catch (ChampServiceException ce) {
424       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
425     } catch (Exception e) {
426       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
427       LoggingUtil.logInternalError(logger, e);
428     } finally {
429       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
430       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "PUT", Long.toString(System.currentTimeMillis() - startTimeInMs));
431     }
432     return response;
433   }
434
435   @DELETE
436   @Path("relationships/{relationshipId}")
437   public Response deleteRelationship(@PathParam("relationshipId") String relationshipId,
438       @QueryParam("transactionId") String tId, @Context HttpHeaders headers, @Context UriInfo uriInfo,
439       @Context HttpServletRequest req) {
440     LoggingUtil.initMdcContext(req, headers);
441     long startTimeInMs = System.currentTimeMillis();
442     logger.info(ChampMsgs.INCOMING_REQUEST, tId, relationshipId);
443
444     Response response = null;
445     try {
446       ChampTransaction transaction = champDataService.getTransaction(tId);
447       if (tId != null && transaction == null) {
448         throw new ChampServiceException("transactionId not found", Status.BAD_REQUEST);
449       }
450       champDataService.deleteRelationship(relationshipId, Optional.ofNullable(transaction));
451       response = Response.status(Status.OK).build();
452
453     } catch (ChampRelationshipNotExistsException e) {
454       response = Response.status(Status.NOT_FOUND).entity(relationshipId + " not found").build();
455     } catch (ChampServiceException ce) {
456       response = Response.status(ce.getHttpStatus()).entity(ce.getMessage()).build();
457     } catch (ChampTransactionException | ChampUnmarshallingException e) {
458       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
459     } finally {
460       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
461       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "DELETE",
462           Long.toString(System.currentTimeMillis() - startTimeInMs));
463     }
464     return response;
465   }
466
467   @GET
468   @Path("relationships/filter/")
469   @Produces(MediaType.APPLICATION_JSON)
470   public Response filterMethod(@Context HttpHeaders headers, @Context UriInfo uriInfo,
471       @Context HttpServletRequest req) {
472     LoggingUtil.initMdcContext(req, headers);
473     long startTimeInMs = System.currentTimeMillis();
474     List<ChampRelationship> list;
475     Map<String, Object> filter = new HashMap<>();
476     for (Map.Entry<String, List<String>> e : uriInfo.getQueryParameters().entrySet()) {
477       filter.put(e.getKey(), e.getValue().get(0));
478     }
479     Response response = null;
480     try {
481       list = champDataService.queryRelationships(filter);
482       response = Response.status(Status.OK).type(MediaType.APPLICATION_JSON).entity(mapper.writeValueAsString(list))
483           .build();
484     } catch (JsonProcessingException e) {
485       e.printStackTrace();
486       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
487     } catch (ChampServiceException e1) {
488       response = Response.status(e1.getHttpStatus()).entity(e1.getMessage()).build();
489     } catch (Exception e) {
490       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
491       LoggingUtil.logInternalError(logger, e);
492     } finally {
493       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
494       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
495     }
496     return response;
497   }
498
499   @POST
500   @Path("transaction")
501   @Produces(MediaType.TEXT_PLAIN)
502   public Response openTransaction(@Context HttpHeaders headers, @Context UriInfo uriInfo,
503       @Context HttpServletRequest req) {
504     LoggingUtil.initMdcContext(req, headers);
505     long startTimeInMs = System.currentTimeMillis();
506     Status s;
507     String transaction = champDataService.openTransaction();
508
509     s = Status.OK;
510     Response response = Response.status(s).entity(transaction).build();
511     logger.info(ChampMsgs.PROCESS_EVENT, "Opened Transaction with ID: " + transaction, s.toString());
512     LoggingUtil.logRestRequest(logger, auditLogger, req, response);
513     metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "POST", Long.toString(System.currentTimeMillis() - startTimeInMs));
514     return response;
515   }
516
517   @GET
518   @Path("transaction/{tId}")
519   public Response getSpecificTransaction(@PathParam("tId") String tId, @Context HttpHeaders headers,
520       @Context UriInfo uriInfo, @Context HttpServletRequest req) {
521     LoggingUtil.initMdcContext(req, headers);
522     long startTimeInMs = System.currentTimeMillis();
523
524     Response response = null;
525     ChampTransaction transaction = champDataService.getTransaction(tId);
526     if (transaction == null) {
527       response = Response.status(Status.NOT_FOUND).entity("transaction " + tId + " not found").build();
528       return response;
529     }
530
531     try {
532       response = Response.status(Status.OK).entity(mapper.writeValueAsString(tId + " is OPEN")).build();
533     } catch (JsonProcessingException e) {
534       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
535     } catch (Exception e) {
536       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
537       LoggingUtil.logInternalError(logger, e);
538     } finally {
539       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
540       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "GET", Long.toString(System.currentTimeMillis() - startTimeInMs));
541     }
542     return response;
543   }
544
545   @PUT
546   @Path("transaction/{tId}")
547   @Produces(MediaType.TEXT_PLAIN)
548   @Consumes(MediaType.APPLICATION_JSON)
549   public Response updateTransaction(String t, @PathParam("tId") String tId, @Context HttpHeaders headers,
550       @Context UriInfo uriInfo, @Context HttpServletRequest req) {
551     LoggingUtil.initMdcContext(req, headers);
552     long startTimeInMs = System.currentTimeMillis();
553     logger.info(ChampMsgs.INCOMING_REQUEST, tId, "COMMIT/ROLLBACK");
554
555     Response response = null;
556     try {
557       JSONObject jsonObj = new JSONObject(t);
558       String method = jsonObj.getString(this.TRANSACTION_METHOD);
559
560       if (method.equals("commit")) {
561         champDataService.commitTransaction(tId);
562         response = Response.status(Status.OK).entity("COMMITTED").build();
563
564       } else if (method.equals("rollback")) {
565         champDataService.rollbackTransaction(tId);
566         response = Response.status(Status.OK).entity("ROLLED BACK").build();
567       } else {
568         response = Response.status(Status.BAD_REQUEST).entity("Invalid Method: " + method).build();
569         return response;
570       }
571
572     } catch (ChampTransactionException e) {
573       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
574     } catch (JSONException e) {
575       response = Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build();
576     } catch (ChampServiceException e) {
577       response = Response.status(e.getHttpStatus()).entity(e.getMessage()).build();
578     } catch (Exception e) {
579       response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
580       LoggingUtil.logInternalError(logger, e);
581     } finally {
582       LoggingUtil.logRestRequest(logger, auditLogger, req, response);
583       metricsLogger.info(ChampMsgs.PROCESSED_REQUEST, "PUT", Long.toString(System.currentTimeMillis() - startTimeInMs));
584     }
585     return response;
586   }
587
588 }