01ca4df9f2619ed98cc68bfa95ea125686fac0a6
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.mso.apihandlerinfra;
22
23 import java.io.IOException;
24 import java.sql.Timestamp;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.ws.rs.Consumes;
31 import javax.ws.rs.DELETE;
32 import javax.ws.rs.GET;
33 import javax.ws.rs.POST;
34 import javax.ws.rs.PUT;
35 import javax.ws.rs.Path;
36 import javax.ws.rs.PathParam;
37 import javax.ws.rs.Produces;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.Response;
40
41 import org.apache.http.HttpResponse;
42 import org.apache.http.HttpStatus;
43 import com.fasterxml.jackson.databind.ObjectMapper;
44 import org.hibernate.Session;
45 import org.json.JSONObject;
46 import org.openecomp.mso.apihandler.common.ErrorNumbers;
47 import org.openecomp.mso.apihandler.common.RequestClient;
48 import org.openecomp.mso.apihandler.common.RequestClientFactory;
49 import org.openecomp.mso.apihandler.common.ResponseHandler;
50 import org.openecomp.mso.apihandlerinfra.Messages;
51 import org.openecomp.mso.apihandlerinfra.MsoException;
52 import org.openecomp.mso.apihandlerinfra.MsoRequest;
53 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.CompareModelsRequest;
54 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.DelE2ESvcResp;
55 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceDeleteRequest;
56 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceRequest;
57 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EUserParam;
58 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.GetE2EServiceInstanceResponse;
59 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.*;
60 import org.openecomp.mso.serviceinstancebeans.ModelInfo;
61 import org.openecomp.mso.serviceinstancebeans.ModelType;
62 import org.openecomp.mso.serviceinstancebeans.RequestDetails;
63 import org.openecomp.mso.serviceinstancebeans.RequestInfo;
64 import org.openecomp.mso.serviceinstancebeans.RequestParameters;
65 import org.openecomp.mso.serviceinstancebeans.ServiceInstancesRequest;
66 import org.openecomp.mso.serviceinstancebeans.SubscriberInfo;
67 import org.openecomp.mso.db.AbstractSessionFactoryManager;
68 import org.openecomp.mso.db.catalog.CatalogDatabase;
69 import org.openecomp.mso.db.catalog.beans.Service;
70 import org.openecomp.mso.db.catalog.beans.ServiceRecipe;
71 import org.openecomp.mso.logger.MessageEnum;
72 import org.openecomp.mso.logger.MsoAlarmLogger;
73 import org.openecomp.mso.logger.MsoLogger;
74 import org.openecomp.mso.properties.MsoDatabaseException;
75 import org.openecomp.mso.requestsdb.OperationStatus;
76 import org.openecomp.mso.requestsdb.RequestsDatabase;
77 import org.openecomp.mso.requestsdb.RequestsDbSessionFactoryManager;
78 import org.openecomp.mso.utils.UUIDChecker;
79
80 import com.wordnik.swagger.annotations.Api;
81 import com.wordnik.swagger.annotations.ApiOperation;
82
83 @Path("/e2eServiceInstances")
84 @Api(value = "/e2eServiceInstances", description = "API Requests for E2E Service Instances")
85 public class E2EServiceInstances {
86
87         private HashMap<String, String> instanceIdMap = new HashMap<>();
88         private static MsoLogger msoLogger = MsoLogger
89                         .getMsoLogger(MsoLogger.Catalog.APIH);
90         private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger();
91         public static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
92         private ServiceInstancesRequest sir = null;
93
94         public static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: ";
95         public static final String EXCEPTION_CREATING_DB_RECORD = "Exception while creating record in DB";
96         public static final String EXCEPTION_COMMUNICATE_BPMN_ENGINE = "Exception while communicate with BPMN engine";
97
98         /**
99          * POST Requests for E2E Service create Instance on a version provided
100          */
101
102         @POST
103         @Path("/{version:[vV][3-5]}")
104         @Consumes(MediaType.APPLICATION_JSON)
105         @Produces(MediaType.APPLICATION_JSON)
106         @ApiOperation(value = "Create an E2E Service Instance on a version provided", response = Response.class)
107         public Response createE2EServiceInstance(String request,
108                         @PathParam("version") String version) {
109
110                 return processE2EserviceInstances(request, Action.createInstance, null,
111                                 version);
112         }
113         
114         /**
115          * PUT Requests for E2E Service update Instance on a version provided
116          */
117
118         @PUT
119         @Path("/{version:[vV][3-5]}/{serviceId}")
120         @Consumes(MediaType.APPLICATION_JSON)
121         @Produces(MediaType.APPLICATION_JSON)
122         @ApiOperation(value = "Update an E2E Service Instance on a version provided and serviceId", response = Response.class)
123         public Response updateE2EServiceInstance(String request,
124                         @PathParam("version") String version,
125                         @PathParam("serviceId") String serviceId) {
126                 
127                 instanceIdMap.put("serviceId", serviceId);
128
129                 return updateE2EserviceInstances(request, Action.updateInstance, instanceIdMap,
130                                 version);
131         }
132
133         /**
134          * DELETE Requests for E2E Service delete Instance on a specified version
135          * and serviceId
136          */
137
138         @DELETE
139         @Path("/{version:[vV][3-5]}/{serviceId}")
140         @Consumes(MediaType.APPLICATION_JSON)
141         @Produces(MediaType.APPLICATION_JSON)
142         @ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class)
143         public Response deleteE2EServiceInstance(String request,
144                         @PathParam("version") String version,
145                         @PathParam("serviceId") String serviceId) {
146
147                 instanceIdMap.put("serviceId", serviceId);
148
149                 return deleteE2EserviceInstances(request, Action.deleteInstance,
150                                 instanceIdMap, version);
151         }
152
153         @GET
154         @Path("/{version:[vV][3-5]}/{serviceId}/operations/{operationId}")
155         @ApiOperation(value = "Find e2eServiceInstances Requests for a given serviceId and operationId", response = Response.class)
156         @Produces(MediaType.APPLICATION_JSON)
157         public Response getE2EServiceInstances(
158                         @PathParam("serviceId") String serviceId,
159                         @PathParam("version") String version,
160                         @PathParam("operationId") String operationId) {
161                 return getE2EServiceInstances(serviceId, operationId);
162         }
163         
164     /**
165          * Scale Requests for E2E Service scale Instance on a specified version 
166      */
167          
168         @POST
169         @Path("/{version:[vV][3-5]}/{serviceId}/scale")
170         @Consumes(MediaType.APPLICATION_JSON)
171         @Produces(MediaType.APPLICATION_JSON)
172         @ApiOperation(value="Scale E2E Service Instance on a specified version",response=Response.class)
173         public Response scaleE2EServiceInstance(String request,
174                                             @PathParam("version") String version,
175                                             @PathParam("serviceId") String serviceId) {
176
177                 msoLogger.debug("------------------scale begin------------------");
178                 instanceIdMap.put("serviceId", serviceId);
179                 return scaleE2EserviceInstances(request, Action.scaleInstance, instanceIdMap, version);
180         }
181         /**
182          * GET Requests for Comparing model of service instance with target version
183          */
184         
185         @POST
186         @Path("/{version:[vV][3-5]}/{serviceId}/modeldifferences")
187         @Consumes(MediaType.APPLICATION_JSON)
188         @Produces(MediaType.APPLICATION_JSON)
189         @ApiOperation(value = "Find added and deleted resources of target model for the e2eserviceInstance on a given serviceId ", response = Response.class)
190         public Response compareModelwithTargetVersion(String request,
191                         @PathParam("serviceId") String serviceId,
192                         @PathParam("version") String version) {
193                 
194                 instanceIdMap.put("serviceId", serviceId);
195                 
196                 return compareModelwithTargetVersion(request, Action.compareModel, instanceIdMap, version);
197         }       
198
199         private Response compareModelwithTargetVersion(String requestJSON, Action action,
200                         HashMap<String, String> instanceIdMap, String version) {
201
202                 String requestId = instanceIdMap.get("serviceId");
203                 long startTime = System.currentTimeMillis();
204                 msoLogger.debug("requestId is: " + requestId);
205
206                 CompareModelsRequest e2eCompareModelReq = null;
207
208                 MsoRequest msoRequest = new MsoRequest(requestId);
209
210                 ObjectMapper mapper = new ObjectMapper();
211                 try {
212                         e2eCompareModelReq = mapper.readValue(requestJSON, CompareModelsRequest.class);
213
214                 } catch (Exception e) {
215
216                         msoLogger.debug("Mapping of request to JSON object failed : ", e);
217                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
218                                         MsoException.ServiceException, "Mapping of request to JSON object failed.  " + e.getMessage(),
219                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
220                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
221                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
222                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
223                                         "Mapping of request to JSON object failed");
224                         msoLogger.debug("End of the transaction, the final response is: " + response.getEntity().toString());
225
226                         return response;
227                 }
228
229                 Response returnResp = runCompareModelBPMWorkflow(e2eCompareModelReq, msoRequest, requestJSON, requestId,
230                                 startTime, action);
231
232                 return returnResp;
233
234         }
235
236         private Response runCompareModelBPMWorkflow(CompareModelsRequest e2eCompareModelReq, MsoRequest msoRequest,
237                         String requestJSON, String requestId, long startTime, Action action) {
238                 
239                 // Define RecipeLookupResult info here instead of query DB for efficiency
240                 String workflowUrl = "/mso/async/services/CompareModelofE2EServiceInstance";
241                 int recipeTimeout = 180;
242
243                 RequestClient requestClient = null;
244                 HttpResponse response = null;
245
246                 long subStartTime = System.currentTimeMillis();
247
248                 try {
249                         requestClient = RequestClientFactory.getRequestClient(workflowUrl, MsoPropertiesUtils.loadMsoProperties());
250
251                         JSONObject jjo = new JSONObject(requestJSON);
252                         String bpmnRequest = jjo.toString();
253
254                         // Capture audit event
255                         msoLogger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
256                         String serviceId = instanceIdMap.get("serviceId");
257                         String serviceType = e2eCompareModelReq.getServiceType();
258                         response = requestClient.post(requestId, false, recipeTimeout, action.name(), serviceId, null, null, null,
259                                         null, null, serviceType, null, null, null, bpmnRequest, null);
260
261                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
262                                         "Successfully received response from BPMN engine", "BPMN", workflowUrl, null);
263                 } catch (Exception e) {
264                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.ERROR,
265                                         MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN",
266                                         workflowUrl, null);
267                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
268                                         MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
269                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
270                         alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL,
271                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
272                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
273                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine",e);
274                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError,
275                                         "Exception while communicate with BPMN engine");
276                         msoLogger.debug("End of the transaction, the final response is: " + resp.getEntity().toString());
277                         return resp;
278                 }
279
280                 if (response == null) {
281                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
282                                         MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
283                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
284                                         MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
285                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
286                                         "Null response from BPMN");
287                         msoLogger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString());
288                         return resp;
289                 }
290
291                 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
292                 int bpelStatus = respHandler.getStatus();
293                 // String responseBody = respHandler.getResponseBody();
294                 // CompareModelsResult modelDiffResponse = new CompareModelsResult();
295
296                 return beplStatusUpdate(requestId, startTime, msoRequest, requestClient, respHandler, bpelStatus, action,
297                                 instanceIdMap);
298         }
299
300         private Response getE2EServiceInstances(String serviceId, String operationId) {
301                 RequestsDatabase requestsDB = RequestsDatabase.getInstance();
302
303                 GetE2EServiceInstanceResponse e2eServiceResponse = new GetE2EServiceInstanceResponse();
304
305                 MsoRequest msoRequest = new MsoRequest(serviceId);
306
307                 long startTime = System.currentTimeMillis();
308
309                 OperationStatus operationStatus = null;
310
311                 try {
312                         operationStatus = requestsDB.getOperationStatus(serviceId,
313                                         operationId);
314
315                 } catch (Exception e) {
316                         msoLogger
317                                         .error(MessageEnum.APIH_DB_ACCESS_EXC,
318                                                         MSO_PROP_APIHANDLER_INFRA,
319                                                         "",
320                                                         "",
321                                                         MsoLogger.ErrorCode.AvailabilityError,
322                                                         "Exception while communciate with Request DB - Infra Request Lookup",
323                                                         e);
324                         msoRequest
325                                         .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
326                         Response response = msoRequest.buildServiceErrorResponse(
327                                         HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
328                                         e.getMessage(),
329                                         ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null);
330                         alarmLogger.sendAlarm("MsoDatabaseAccessError",
331                                         MsoAlarmLogger.CRITICAL, Messages.errors
332                                                         .get(ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB));
333                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
334                                         MsoLogger.ResponseCode.DBAccessError,
335                                         "Exception while communciate with Request DB");
336                         msoLogger.debug("End of the transaction, the final response is: "
337                                         + (String) response.getEntity());
338                         return response;
339
340                 }
341
342                 if (operationStatus == null) {
343                         Response resp = msoRequest.buildServiceErrorResponse(
344                                         HttpStatus.SC_NO_CONTENT, MsoException.ServiceException,
345                                         "E2E serviceId " + serviceId + " is not found in DB",
346                                         ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null);
347                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
348                                         MSO_PROP_APIHANDLER_INFRA, "", "",
349                                         MsoLogger.ErrorCode.BusinessProcesssError,
350                                         "Null response from RequestDB when searching by serviceId");
351                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
352                                         MsoLogger.ResponseCode.DataNotFound,
353                                         "Null response from RequestDB when searching by serviceId");
354                         msoLogger.debug("End of the transaction, the final response is: "
355                                         + (String) resp.getEntity());
356                         return resp;
357
358                 }
359
360                 e2eServiceResponse.setOperationStatus(operationStatus);
361
362                 return Response.status(200).entity(e2eServiceResponse).build();
363         }
364
365         private Response deleteE2EserviceInstances(String requestJSON,
366                         Action action, HashMap<String, String> instanceIdMap, String version) {
367                 // TODO should be a new one or the same service instance Id
368                 String requestId = instanceIdMap.get("serviceId");
369                 long startTime = System.currentTimeMillis();
370                 msoLogger.debug("requestId is: " + requestId);
371                 E2EServiceInstanceDeleteRequest e2eDelReq = null;
372
373                 MsoRequest msoRequest = new MsoRequest(requestId);
374
375                 ObjectMapper mapper = new ObjectMapper();
376                 try {
377                         e2eDelReq = mapper.readValue(requestJSON,
378                                         E2EServiceInstanceDeleteRequest.class);
379
380                 } catch (Exception e) {
381
382                         msoLogger.debug("Mapping of request to JSON object failed : ", e);
383                         Response response = msoRequest.buildServiceErrorResponse(
384                                         HttpStatus.SC_BAD_REQUEST,
385                                         MsoException.ServiceException,
386                                         "Mapping of request to JSON object failed.  "
387                                                         + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER,
388                                         null);
389                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
390                                         MSO_PROP_APIHANDLER_INFRA, "", "",
391                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
392                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
393                                         MsoLogger.ResponseCode.SchemaError,
394                                         "Mapping of request to JSON object failed");
395                         msoLogger.debug("End of the transaction, the final response is: "
396                                         + (String) response.getEntity());
397                         createOperationStatusRecordForError(action, requestId);
398                         return response;
399                 }
400
401                 CatalogDatabase db = null;
402                 RecipeLookupResult recipeLookupResult = null;
403                 try {
404                         db = CatalogDatabase.getInstance();
405                         //TODO  Get the service template model version uuid from AAI.
406                         recipeLookupResult = getServiceInstanceOrchestrationURI(db, null, action);
407                 } catch (Exception e) {
408                         msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC,
409                                         MSO_PROP_APIHANDLER_INFRA, "", "",
410                                         MsoLogger.ErrorCode.AvailabilityError,
411                                         "Exception while communciate with Catalog DB", e);
412                         msoRequest
413                                         .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
414                         Response response = msoRequest.buildServiceErrorResponse(
415                                         HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
416                                         "No communication to catalog DB " + e.getMessage(),
417                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
418                         alarmLogger.sendAlarm("MsoDatabaseAccessError",
419                                         MsoAlarmLogger.CRITICAL, Messages.errors
420                                                         .get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
421                         msoRequest.createRequestRecord(Status.FAILED, action);
422                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
423                                         MsoLogger.ResponseCode.DBAccessError,
424                                         "Exception while communciate with DB");
425                         msoLogger.debug(END_OF_THE_TRANSACTION
426                                         + (String) response.getEntity());
427                         return response;
428                 } finally {
429                         closeCatalogDB(db);
430                 }
431                 if (recipeLookupResult == null) {
432                         msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
433                                         MSO_PROP_APIHANDLER_INFRA, "", "",
434                                         MsoLogger.ErrorCode.DataError, "No recipe found in DB");
435                         msoRequest
436                                         .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
437                         Response response = msoRequest.buildServiceErrorResponse(
438                                         HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
439                                         "Recipe does not exist in catalog DB",
440                                         ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);
441                         msoRequest.createRequestRecord(Status.FAILED, action);
442                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
443                                         MsoLogger.ResponseCode.DataNotFound,
444                                         "No recipe found in DB");
445                         msoLogger.debug(END_OF_THE_TRANSACTION
446                                         + (String) response.getEntity());
447                         createOperationStatusRecordForError(action, requestId);
448                         return response;
449                 }
450
451                 RequestClient requestClient = null;
452                 HttpResponse response = null;
453
454                 long subStartTime = System.currentTimeMillis();
455                 // String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
456
457                 try {
458                         requestClient = RequestClientFactory.getRequestClient(
459                                         recipeLookupResult.getOrchestrationURI(),
460                                         MsoPropertiesUtils.loadMsoProperties());
461
462                         JSONObject jjo = new JSONObject(requestJSON);
463                         jjo.put("operationId", UUIDChecker.generateUUID(msoLogger));
464
465                         String bpmnRequest = jjo.toString();
466
467                         // Capture audit event
468                         msoLogger
469                                         .debug("MSO API Handler Posting call to BPEL engine for url: "
470                                                         + requestClient.getUrl());
471                         String serviceId = instanceIdMap.get("serviceId");
472                         String serviceInstanceType = e2eDelReq.getServiceType();
473                         response = requestClient.post(requestId, false,
474                                         recipeLookupResult.getRecipeTimeout(), action.name(),
475                                         serviceId, null, null, null, null, null, serviceInstanceType,
476                                         null, null, null, bpmnRequest, recipeLookupResult.getRecipeParamXsd());
477
478                         msoLogger.recordMetricEvent(subStartTime,
479                                         MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
480                                         "Successfully received response from BPMN engine", "BPMN",
481                                         recipeLookupResult.getOrchestrationURI(), null);
482                 } catch (Exception e) {
483                         msoLogger.recordMetricEvent(subStartTime,
484                                         MsoLogger.StatusCode.ERROR,
485                                         MsoLogger.ResponseCode.CommunicationError,
486                                         "Exception while communicate with BPMN engine", "BPMN",
487                                         recipeLookupResult.getOrchestrationURI(), null);
488                         Response resp = msoRequest.buildServiceErrorResponse(
489                                         HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
490                                         "Failed calling bpmn " + e.getMessage(),
491                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
492                         alarmLogger.sendAlarm("MsoConfigurationError",
493                                         MsoAlarmLogger.CRITICAL,
494                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
495                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
496                                         MSO_PROP_APIHANDLER_INFRA, "", "",
497                                         MsoLogger.ErrorCode.AvailabilityError,
498                                         "Exception while communicate with BPMN engine");
499                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
500                                         MsoLogger.ResponseCode.CommunicationError,
501                                         "Exception while communicate with BPMN engine");
502                         msoLogger.debug("End of the transaction, the final response is: "
503                                         + (String) resp.getEntity());
504                         createOperationStatusRecordForError(action, requestId);
505                         return resp;
506                 }
507
508                 if (response == null) {
509                         Response resp = msoRequest.buildServiceErrorResponse(
510                                         HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
511                                         "bpelResponse is null",
512                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
513                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
514                                         MSO_PROP_APIHANDLER_INFRA, "", "",
515                                         MsoLogger.ErrorCode.BusinessProcesssError,
516                                         "Null response from BPEL");
517                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
518                                         MsoLogger.ResponseCode.InternalError,
519                                         "Null response from BPMN");
520                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity());
521                         createOperationStatusRecordForError(action, requestId);
522                         return resp;
523                 }
524
525                 ResponseHandler respHandler = new ResponseHandler(response,
526                                 requestClient.getType());
527                 int bpelStatus = respHandler.getStatus();
528
529                 return beplStatusUpdate(requestId, startTime, msoRequest,
530                                 requestClient, respHandler, bpelStatus, action, instanceIdMap);
531         }
532
533         private Response updateE2EserviceInstances(String requestJSON, Action action,
534                         HashMap<String, String> instanceIdMap, String version) {
535
536                 String requestId = UUIDChecker.generateUUID(msoLogger);
537                 long startTime = System.currentTimeMillis();
538                 msoLogger.debug("requestId is: " + requestId);
539                 E2EServiceInstanceRequest e2eSir = null;
540                 String serviceId = instanceIdMap.get("serviceId");
541
542                 MsoRequest msoRequest = new MsoRequest(requestId);
543                 ObjectMapper mapper = new ObjectMapper();
544                 try {
545                         e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
546
547                 } catch (Exception e) {
548           
549                         msoLogger.debug("Mapping of request to JSON object failed : ", e);
550                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
551                                         MsoException.ServiceException, "Mapping of request to JSON object failed.  " + e.getMessage(),
552                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
553                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
554                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
555                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
556                                         "Mapping of request to JSON object failed");
557                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
558                         return response;
559                 }
560
561                 mapReqJsonToSvcInstReq(e2eSir, requestJSON);
562                 sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
563                 try {
564                         msoRequest.parse(sir, instanceIdMap, action, version, requestJSON);
565                 } catch (Exception e) {
566                         msoLogger.debug("Validation failed: ", e);
567                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
568                                         MsoException.ServiceException, "Error parsing request.  " + e.getMessage(),
569                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
570                         if (msoRequest.getRequestId() != null) {
571                                 msoLogger.debug("Logging failed message to the database");
572                         }
573                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
574                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
575                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
576                                         "Validation of the input request failed");
577                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
578                         return response;
579                 }
580                 
581                 //check for the current operation status
582 //              Response resp = checkE2ESvcInstStatus(action, serviceId, startTime, msoRequest);
583 //              if(resp != null && resp.getStatus() != 200) {
584 //                      return resp;
585 //              }
586                 
587                 CatalogDatabase db = null;
588                 RecipeLookupResult recipeLookupResult = null;
589                 try {
590                         db = CatalogDatabase.getInstance();
591                         recipeLookupResult = getServiceInstanceOrchestrationURI(db, e2eSir.getService().getServiceUuid(), action);
592                 } catch (Exception e) {
593                         msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "",
594                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
595                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
596                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
597                                         MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
598                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
599                         alarmLogger.sendAlarm("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL,
600                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
601                         
602                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
603                                         "Exception while communciate with DB");
604                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
605                         
606                         return response;
607                 } finally {
608                         closeCatalogDB(db);
609                 }
610
611                 if (recipeLookupResult == null) {
612                         msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "",
613                                         MsoLogger.ErrorCode.DataError, "No recipe found in DB");
614                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
615                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
616                                         MsoException.ServiceException, "Recipe does not exist in catalog DB",
617                                         ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);
618                 
619                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound,
620                                         "No recipe found in DB");
621                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
622
623                         return response;
624                 }
625
626                 String serviceInstanceType = e2eSir.getService().getServiceType();
627
628                 RequestClient requestClient = null;
629                 HttpResponse response = null;
630
631                 long subStartTime = System.currentTimeMillis();
632                 String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
633
634                 try {
635                         requestClient = RequestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI(),
636                                         MsoPropertiesUtils.loadMsoProperties());
637
638                         // Capture audit event
639                         msoLogger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
640
641                         response = requestClient.post(requestId, false, recipeLookupResult.getRecipeTimeout(), action.name(),
642                                         serviceId, null, null, null, null, null, serviceInstanceType, null, null, null, sirRequestJson,
643                                         recipeLookupResult.getRecipeParamXsd());
644
645                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
646                                         "Successfully received response from BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI(),
647                                         null);
648                 } catch (Exception e) {
649                         msoLogger.debug("Exception while communicate with BPMN engine", e);
650                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.ERROR,
651                                         MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN",
652                                         recipeLookupResult.getOrchestrationURI(), null);
653                         Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
654                                         MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
655                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
656                         alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL,
657                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
658                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
659                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
660                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError,
661                                         "Exception while communicate with BPMN engine");
662                         msoLogger.debug("End of the transaction, the final response is: " + (String) getBPMNResp.getEntity());
663
664                         return getBPMNResp;
665                 }
666
667                 if (response == null) {
668                         Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
669                                         MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
670                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
671                                         MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
672                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
673                                         "Null response from BPMN");
674                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) getBPMNResp.getEntity());
675
676                         return getBPMNResp;
677                 }
678
679                 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
680                 int bpelStatus = respHandler.getStatus();
681
682                 return beplStatusUpdate(serviceId, startTime, msoRequest, requestClient, respHandler, bpelStatus, action, instanceIdMap);
683         }
684
685         private Response checkE2ESvcInstStatus(Action action, String serviceId, long startTime, MsoRequest msoRequest) {
686                 OperationStatus curStatus = null;
687 //              String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
688                 String requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
689                 try {
690                         if (!(serviceId == null && "service".equals(requestScope) && (action == Action.updateInstance))) {                          
691                                 curStatus = chkSvcInstOperStatusbySvcId(serviceId);
692                         }
693                 } catch (Exception e) {
694                         msoLogger.error(MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "",
695                                         MsoLogger.ErrorCode.DataError, "Error during current operation status check ", e);
696
697                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
698                                         MsoException.ServiceException, e.getMessage(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null);
699
700                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
701                                         "Error during current operation status check");
702                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
703                         return response;
704                 }
705
706                 if ("processing".equalsIgnoreCase("curStatus != null && curStatus.getResult() != null && curStatus.getResult()")) {
707                         String chkMessage = "Error: Locked instance - This " + requestScope + " (" + serviceId + ") "
708                                         + "now being worked with a status of " + curStatus.getResult() 
709                                         + ". The latest workflow of instance must be finished or cleaned up.";
710
711                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT,
712                                         MsoException.ServiceException, chkMessage, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null);
713
714                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict,
715                                         chkMessage);
716
717                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
718
719                         return response;
720                 }
721                 
722                 return Response.status(200).entity(null).build();
723         }
724         
725         private Response processE2EserviceInstances(String requestJSON, Action action,
726                         HashMap<String, String> instanceIdMap, String version) {
727
728                 String requestId = UUIDChecker.generateUUID(msoLogger);
729                 long startTime = System.currentTimeMillis();
730                 msoLogger.debug("requestId is: " + requestId);
731                 E2EServiceInstanceRequest e2eSir = null;
732
733                 MsoRequest msoRequest = new MsoRequest(requestId);
734                 ObjectMapper mapper = new ObjectMapper();
735                 try {
736                         e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
737
738                 } catch (Exception e) {
739           //TODO update the service name
740           this.createOperationStatusRecordForError(action, requestId);
741                   
742                         msoLogger.debug("Mapping of request to JSON object failed : ", e);
743                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
744                                         MsoException.ServiceException, "Mapping of request to JSON object failed.  " + e.getMessage(),
745                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
746                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
747                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
748                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
749                                         "Mapping of request to JSON object failed");
750                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
751                         return response;
752                 }
753
754                 mapReqJsonToSvcInstReq(e2eSir, requestJSON);
755                 sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
756                 try {
757                         msoRequest.parse(sir, instanceIdMap, action, version, requestJSON);
758                 } catch (Exception e) {
759                         msoLogger.debug("Validation failed: ", e);
760                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
761                                         MsoException.ServiceException, "Error parsing request.  " + e.getMessage(),
762                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
763                         if (msoRequest.getRequestId() != null) {
764                                 msoLogger.debug("Logging failed message to the database");
765                                 //TODO update the service name
766                           this.createOperationStatusRecordForError(action, requestId);
767                         }
768                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
769                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
770                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
771                                         "Validation of the input request failed");
772                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
773                         return response;
774                 }
775                 
776                 OperationStatus dup = null;
777                 String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
778                 String requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
779                 try {
780                         if (!(instanceName == null && "service".equals(requestScope)
781                                         && (action == Action.createInstance || action == Action.activateInstance))) {
782                           //TODO : Need to check for the duplicate record from the operation status,
783                           //TODO : commenting this check for unblocking current testing for now...  induces dead code...
784                                 dup = chkDuplicateServiceNameInOperStatus( instanceName);
785                         }
786                 } catch (Exception e) {
787                         msoLogger.error(MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "",
788                                         MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e);
789
790                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
791                                         MsoException.ServiceException, e.getMessage(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null);
792
793                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
794                                         "Error during duplicate check");
795                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
796                         return response;
797                 }
798
799                 if (dup != null) {
800                         // Found the duplicate record. Return the appropriate error.
801                         String instance = null;
802                         if (instanceName != null) {
803                                 instance = instanceName;
804                         } else {
805                                 instance = instanceIdMap.get(requestScope + "InstanceId");
806                         }
807                         String dupMessage = "Error: Locked instance - This " + requestScope + " (" + instance + ") "
808                                         + "already has a request being worked with a status of " + dup.getProgress() + " (ServiceId - "
809                                         + dup.getServiceId() + "). The existing request must finish or be cleaned up before proceeding.";
810
811                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT,
812                                         MsoException.ServiceException, dupMessage, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null);
813
814                         msoLogger.warn(MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError,
815                                         "Duplicate request - Subscriber already has a request for this service");
816                         
817                         
818                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict,
819                                         dupMessage);
820                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
821                         createOperationStatusRecordForError(action, requestId);
822                         return response;
823                 }
824                 
825                 CatalogDatabase db = null;
826                 RecipeLookupResult recipeLookupResult = null;
827                 try {
828                         db = CatalogDatabase.getInstance();
829                         recipeLookupResult = getServiceInstanceOrchestrationURI(db, e2eSir.getService().getServiceUuid(), action);
830                 } catch (Exception e) {
831                         msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "",
832                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
833                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
834                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
835                                         MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
836                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
837                         alarmLogger.sendAlarm("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL,
838                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
839                         
840                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
841                                         "Exception while communciate with DB");
842                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
843                         createOperationStatusRecordForError(action, requestId);
844                         return response;
845                 } finally {
846                         closeCatalogDB(db);
847                 }
848
849                 if (recipeLookupResult == null) {
850                         msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "",
851                                         MsoLogger.ErrorCode.DataError, "No recipe found in DB");
852                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
853                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
854                                         MsoException.ServiceException, "Recipe does not exist in catalog DB",
855                                         ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);
856                 
857                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound,
858                                         "No recipe found in DB");
859                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
860                         createOperationStatusRecordForError(action, requestId);
861                         return response;
862                 }
863 //              try {
864 //                      msoRequest.createRequestRecord(Status.PENDING, action);
865 //                      //createOperationStatusRecord(action, requestId);
866 //              } catch (Exception e) {
867 //                      msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC_REASON, "Exception while creating record in DB", "", "",
868 //                                      MsoLogger.ErrorCode.SchemaError, "Exception while creating record in DB", e);
869 //                      msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
870 //                      Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
871 //                                      MsoException.ServiceException, "Exception while creating record in DB " + e.getMessage(),
872 //                                      ErrorNumbers.SVC_BAD_PARAMETER, null);
873 //                      msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
874 //                                      "Exception while creating record in DB");
875 //                      msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
876 //                      return response;
877 //              }
878
879                 String serviceInstanceType = e2eSir.getService().getServiceType();
880
881                 String serviceId = "";
882                 RequestClient requestClient = null;
883                 HttpResponse response = null;
884
885                 long subStartTime = System.currentTimeMillis();
886                 String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
887
888                 try {
889                         requestClient = RequestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI(),
890                                         MsoPropertiesUtils.loadMsoProperties());
891
892                         // Capture audit event
893                         msoLogger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
894
895                         response = requestClient.post(requestId, false, recipeLookupResult.getRecipeTimeout(), action.name(),
896                                         serviceId, null, null, null, null, null, serviceInstanceType, null, null, null, sirRequestJson,
897                                         recipeLookupResult.getRecipeParamXsd());
898
899                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
900                                         "Successfully received response from BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI(),
901                                         null);
902                 } catch (Exception e) {
903                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.ERROR,
904                                         MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN",
905                                         recipeLookupResult.getOrchestrationURI(), null);
906                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
907                                         MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
908                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
909                         alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL,
910                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
911                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
912                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
913                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError,
914                                         "Exception while communicate with BPMN engine");
915                         msoLogger.debug("End of the transaction, the final response is: " + (String) resp.getEntity());
916                         createOperationStatusRecordForError(action, requestId);
917                         return resp;
918                 }
919
920                 if (response == null) {
921                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
922                                         MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
923                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
924                                         MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
925                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
926                                         "Null response from BPMN");
927                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity());
928                         return resp;
929                 }
930
931                 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
932                 int bpelStatus = respHandler.getStatus();
933
934                 return beplStatusUpdate(requestId, startTime, msoRequest, requestClient, respHandler, bpelStatus, action, instanceIdMap);
935         }
936
937    private Response scaleE2EserviceInstances(String requestJSON,
938                                                Action action, HashMap<String, String> instanceIdMap, String version) {
939
940         String requestId = instanceIdMap.get("serviceId");
941         long startTime = System.currentTimeMillis();
942         msoLogger.debug("requestId is: " + requestId);
943                 E2EServiceInstanceScaleRequest e2eScaleReq = null;
944
945         MsoRequest msoRequest = new MsoRequest(requestId);
946
947         ObjectMapper mapper = new ObjectMapper();
948         try {
949                 e2eScaleReq = mapper.readValue(requestJSON,
950                                         E2EServiceInstanceScaleRequest.class);
951
952         } catch (Exception e) {
953
954             msoLogger.debug("Mapping of request to JSON object failed : ", e);
955             Response response = msoRequest.buildServiceErrorResponse(
956                     HttpStatus.SC_BAD_REQUEST,
957                     MsoException.ServiceException,
958                     "Mapping of request to JSON object failed.  "
959                             + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER,
960                     null);
961             msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
962                     MSO_PROP_APIHANDLER_INFRA, "", "",
963                     MsoLogger.ErrorCode.SchemaError, requestJSON, e);
964             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
965                     MsoLogger.ResponseCode.SchemaError,
966                     "Mapping of request to JSON object failed");
967             msoLogger.debug("End of the transaction, the final response is: "
968                     + (String) response.getEntity());
969             createOperationStatusRecordForError(action, requestId);
970             return response;
971         }
972
973         CatalogDatabase db = null;
974         RecipeLookupResult recipeLookupResult = null;
975         try {
976             db = CatalogDatabase.getInstance();
977                         //TODO  Get the service template model version uuid from AAI.
978                         recipeLookupResult = getServiceInstanceOrchestrationURI(db, null, action);
979         } catch (Exception e) {
980             msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC,
981                     MSO_PROP_APIHANDLER_INFRA, "", "",
982                     MsoLogger.ErrorCode.AvailabilityError,
983                     "Exception while communciate with Catalog DB", e);
984             msoRequest
985                     .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
986             Response response = msoRequest.buildServiceErrorResponse(
987                     HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
988                     "No communication to catalog DB " + e.getMessage(),
989                     ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
990             alarmLogger.sendAlarm("MsoDatabaseAccessError",
991                     MsoAlarmLogger.CRITICAL, Messages.errors
992                             .get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
993             msoRequest.createRequestRecord(Status.FAILED, action);
994             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
995                     MsoLogger.ResponseCode.DBAccessError,
996                     "Exception while communciate with DB");
997             msoLogger.debug(END_OF_THE_TRANSACTION
998                     + (String) response.getEntity());
999             return response;
1000         } finally {
1001             closeCatalogDB(db);
1002         }
1003         if (recipeLookupResult == null) {
1004             msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
1005                     MSO_PROP_APIHANDLER_INFRA, "", "",
1006                     MsoLogger.ErrorCode.DataError, "No recipe found in DB");
1007             msoRequest
1008                     .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
1009             Response response = msoRequest.buildServiceErrorResponse(
1010                     HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
1011                     "Recipe does not exist in catalog DB",
1012                     ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);
1013             msoRequest.createRequestRecord(Status.FAILED, action);
1014             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
1015                     MsoLogger.ResponseCode.DataNotFound,
1016                     "No recipe found in DB");
1017             msoLogger.debug(END_OF_THE_TRANSACTION
1018                     + (String) response.getEntity());
1019             createOperationStatusRecordForError(action, requestId);
1020             return response;
1021         }
1022
1023         RequestClient requestClient = null;
1024         HttpResponse response = null;
1025
1026         long subStartTime = System.currentTimeMillis();
1027         // String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
1028
1029         try {
1030             requestClient = RequestClientFactory.getRequestClient(
1031                     recipeLookupResult.getOrchestrationURI(),
1032                     MsoPropertiesUtils.loadMsoProperties());
1033
1034             JSONObject jjo = new JSONObject(requestJSON);
1035             jjo.put("operationId", UUIDChecker.generateUUID(msoLogger));
1036
1037             String bpmnRequest = jjo.toString();
1038
1039             // Capture audit event
1040             msoLogger
1041                     .debug("MSO API Handler Posting call to BPEL engine for url: "
1042                             + requestClient.getUrl());
1043             String serviceId = instanceIdMap.get("serviceId");
1044             String serviceInstanceType = e2eScaleReq.getService().getServiceType();
1045             response = requestClient.post(requestId, false,
1046                                         recipeLookupResult.getRecipeTimeout(), action.name(),
1047                                         serviceId, null, null, null, null, null, serviceInstanceType,
1048                                         null, null, null, bpmnRequest, recipeLookupResult.getRecipeParamXsd());
1049
1050             msoLogger.recordMetricEvent(subStartTime,
1051                     MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
1052                     "Successfully received response from BPMN engine", "BPMN",
1053                     recipeLookupResult.getOrchestrationURI(), null);
1054         } catch (Exception e) {
1055             msoLogger.recordMetricEvent(subStartTime,
1056                     MsoLogger.StatusCode.ERROR,
1057                     MsoLogger.ResponseCode.CommunicationError,
1058                     "Exception while communicate with BPMN engine", "BPMN",
1059                     recipeLookupResult.getOrchestrationURI(), null);
1060             Response resp = msoRequest.buildServiceErrorResponse(
1061                     HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
1062                     "Failed calling bpmn " + e.getMessage(),
1063                     ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
1064             alarmLogger.sendAlarm("MsoConfigurationError",
1065                     MsoAlarmLogger.CRITICAL,
1066                     Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
1067             msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
1068                     MSO_PROP_APIHANDLER_INFRA, "", "",
1069                     MsoLogger.ErrorCode.AvailabilityError,
1070                     "Exception while communicate with BPMN engine",e);
1071             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
1072                     MsoLogger.ResponseCode.CommunicationError,
1073                     "Exception while communicate with BPMN engine");
1074             msoLogger.debug("End of the transaction, the final response is: "
1075                     + (String) resp.getEntity());
1076             createOperationStatusRecordForError(action, requestId);
1077             return resp;
1078         }
1079
1080         if (response == null) {
1081             Response resp = msoRequest.buildServiceErrorResponse(
1082                     HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
1083                     "bpelResponse is null",
1084                     ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
1085             msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
1086                     MSO_PROP_APIHANDLER_INFRA, "", "",
1087                     MsoLogger.ErrorCode.BusinessProcesssError,
1088                     "Null response from BPEL");
1089             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
1090                     MsoLogger.ResponseCode.InternalError,
1091                     "Null response from BPMN");
1092             msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity());
1093             createOperationStatusRecordForError(action, requestId);
1094             return resp;
1095         }
1096
1097         ResponseHandler respHandler = new ResponseHandler(response,
1098                 requestClient.getType());
1099         int bpelStatus = respHandler.getStatus();
1100
1101         return beplStatusUpdate(requestId, startTime, msoRequest,
1102                 requestClient, respHandler, bpelStatus, action, instanceIdMap);
1103     }
1104
1105         private void closeCatalogDB(CatalogDatabase db) {
1106                 if (db != null) {
1107                         db.close();
1108                 }
1109         }
1110
1111         private Response beplStatusUpdate(String serviceId, long startTime,
1112                         MsoRequest msoRequest, RequestClient requestClient,
1113                         ResponseHandler respHandler, int bpelStatus, Action action,
1114                         HashMap<String, String> instanceIdMap) {
1115                 // BPMN accepted the request, the request is in progress
1116                 if (bpelStatus == HttpStatus.SC_ACCEPTED) {
1117                         String camundaJSONResponseBody = respHandler.getResponseBody();
1118                         msoLogger.debug("Received from Camunda: " + camundaJSONResponseBody);
1119
1120                         // currently only for delete case we update the status here
1121                         if (action == Action.deleteInstance) {
1122                                 ObjectMapper mapper = new ObjectMapper();
1123                                 try {
1124                                         DelE2ESvcResp jo = mapper.readValue(
1125                                                         camundaJSONResponseBody, DelE2ESvcResp.class);
1126                                         String operationId = jo.getOperationId();
1127                                 this.createOperationStatusRecord("DELETE", serviceId,
1128                                                                 operationId);
1129                                 } catch (Exception ex) {
1130                                         msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
1131                                                         requestClient.getUrl(), "", "",
1132                                                         MsoLogger.ErrorCode.BusinessProcesssError,
1133                                                         "Response from BPEL engine is failed with HTTP Status="
1134                                                                         + bpelStatus);
1135                                 }
1136                         }
1137                         
1138                         msoLogger.recordAuditEvent(startTime,
1139                                         MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
1140                                         "BPMN accepted the request, the request is in progress");
1141                         msoLogger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody);
1142                         return Response.status(HttpStatus.SC_ACCEPTED)
1143                                         .entity(camundaJSONResponseBody).build();
1144                 } else {
1145                         List<String> variables = new ArrayList<>();
1146                         variables.add(bpelStatus + "");
1147                         String camundaJSONResponseBody = respHandler.getResponseBody();
1148                         if (camundaJSONResponseBody != null
1149                                         && !camundaJSONResponseBody.isEmpty()) {
1150                                 Response resp = msoRequest.buildServiceErrorResponse(
1151                                                 bpelStatus, MsoException.ServiceException,
1152                                                 "Request Failed due to BPEL error with HTTP Status= %1 "
1153                                                                 + '\n' + camundaJSONResponseBody,
1154                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables);
1155                                 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
1156                                                 requestClient.getUrl(), "", "",
1157                                                 MsoLogger.ErrorCode.BusinessProcesssError,
1158                                                 "Response from BPEL engine is failed with HTTP Status="
1159                                                                 + bpelStatus);
1160                                 msoLogger.recordAuditEvent(startTime,
1161                                                 MsoLogger.StatusCode.ERROR,
1162                                                 MsoLogger.ResponseCode.InternalError,
1163                                                 "Response from BPMN engine is failed");
1164                                 msoLogger.debug(END_OF_THE_TRANSACTION
1165                                                 + (String) resp.getEntity());
1166                                 return resp;
1167                         } else {
1168                                 Response resp = msoRequest
1169                                                 .buildServiceErrorResponse(
1170                                                                 bpelStatus,
1171                                                                 MsoException.ServiceException,
1172                                                                 "Request Failed due to BPEL error with HTTP Status= %1",
1173                                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
1174                                                                 variables);
1175                                 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
1176                                                 requestClient.getUrl(), "", "",
1177                                                 MsoLogger.ErrorCode.BusinessProcesssError,
1178                                                 "Response from BPEL engine is empty");
1179                                 msoLogger.recordAuditEvent(startTime,
1180                                                 MsoLogger.StatusCode.ERROR,
1181                                                 MsoLogger.ResponseCode.InternalError,
1182                                                 "Response from BPEL engine is empty");
1183                                 msoLogger.debug(END_OF_THE_TRANSACTION
1184                                                 + (String) resp.getEntity());
1185                                 return resp;
1186                         }
1187                 }
1188         }
1189
1190         /**
1191          * Getting recipes from catalogDb
1192          * 
1193          * @param db the catalog db
1194          * @param serviceModelUUID the service model version uuid
1195          * @param action the action for the service
1196          * @return the service recipe result
1197          */
1198         private RecipeLookupResult getServiceInstanceOrchestrationURI(
1199                         CatalogDatabase db, String serviceModelUUID, Action action) {
1200
1201                 RecipeLookupResult recipeLookupResult = getServiceURI(db, serviceModelUUID, action);
1202
1203                 if (recipeLookupResult != null) {
1204                         msoLogger.debug("Orchestration URI is: "
1205                                         + recipeLookupResult.getOrchestrationURI()
1206                                         + ", recipe Timeout is: "
1207                                         + Integer.toString(recipeLookupResult.getRecipeTimeout()));
1208                 } else {
1209                         msoLogger.debug("No matching recipe record found");
1210                 }
1211                 return recipeLookupResult;
1212         }
1213
1214         /**
1215          * Getting recipes from catalogDb
1216          * If Service recipe is not set, use default recipe, if set , use special recipe.
1217          * @param db the catalog db
1218          * @param serviceModelUUID the service version uuid
1219          * @param action the action of the service.
1220          * @return the service recipe result.
1221          */
1222         private RecipeLookupResult getServiceURI(CatalogDatabase db, String serviceModelUUID, Action action) {
1223
1224                 String defaultServiceModelName = "UUI_DEFAULT";
1225
1226                 Service defaultServiceRecord = db
1227                                 .getServiceByModelName(defaultServiceModelName);
1228                 ServiceRecipe defaultRecipe = db.getServiceRecipeByModelUUID(
1229                         defaultServiceRecord.getModelUUID(), action.name());
1230                 //set recipe as default generic recipe
1231                 ServiceRecipe recipe = defaultRecipe;
1232                 //check the service special recipe 
1233                 if(null != serviceModelUUID && ! serviceModelUUID.isEmpty()){
1234                       ServiceRecipe serviceSpecialRecipe = db.getServiceRecipeByModelUUID(
1235                               serviceModelUUID, action.name());
1236                       if(null != serviceSpecialRecipe){
1237                           //set service special recipe.
1238                           recipe = serviceSpecialRecipe;
1239                       }
1240                 }       
1241                 
1242                 if (recipe == null) {
1243                         return null;
1244                 }
1245                 return new RecipeLookupResult(recipe.getOrchestrationUri(),
1246                                 recipe.getRecipeTimeout(), recipe.getServiceParamXSD());
1247
1248         }
1249
1250         /**
1251          * Converting E2EServiceInstanceRequest to ServiceInstanceRequest and
1252          * passing it to camunda engine.
1253          * 
1254          * @param e2eSir
1255          * @return
1256          */
1257         private String mapReqJsonToSvcInstReq(E2EServiceInstanceRequest e2eSir,
1258                         String requestJSON) {
1259
1260                 sir = new ServiceInstancesRequest();
1261
1262                 String returnString = null;
1263                 RequestDetails requestDetails = new RequestDetails();
1264                 ModelInfo modelInfo = new ModelInfo();
1265
1266                 // ModelInvariantId
1267                 modelInfo.setModelInvariantId(e2eSir.getService().getServiceInvariantUuid());
1268
1269                 // modelNameVersionId
1270                 modelInfo.setModelNameVersionId(e2eSir.getService().getServiceUuid());
1271
1272                 // String modelInfoValue =
1273                 // e2eSir.getService().getParameters().getNodeTemplateName();
1274                 // String[] arrayOfInfo = modelInfoValue.split(":");
1275                 // String modelName = arrayOfInfo[0];
1276                 // String modelVersion = arrayOfInfo[1];
1277
1278                 // TODO: To ensure, if we dont get the values from the UUI
1279                 String modelName = "voLTE";
1280                 String modelVersion = "1.0";
1281                 // modelName
1282                 modelInfo.setModelName(modelName);
1283
1284                 // modelVersion
1285                 modelInfo.setModelVersion(modelVersion);
1286
1287                 // modelType
1288                 modelInfo.setModelType(ModelType.service);
1289
1290                 // setting modelInfo to requestDetails
1291                 requestDetails.setModelInfo(modelInfo);
1292
1293                 SubscriberInfo subscriberInfo = new SubscriberInfo();
1294
1295                 // globalsubscriberId
1296                 subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getGlobalSubscriberId());
1297
1298                 // setting subscriberInfo to requestDetails
1299                 requestDetails.setSubscriberInfo(subscriberInfo);
1300
1301                 RequestInfo requestInfo = new RequestInfo();
1302
1303                 // instanceName
1304                 requestInfo.setInstanceName(e2eSir.getService().getName());
1305
1306                 // source
1307                 requestInfo.setSource("UUI");
1308
1309                 // suppressRollback
1310                 requestInfo.setSuppressRollback(true);
1311
1312                 // setting requestInfo to requestDetails
1313                 requestDetails.setRequestInfo(requestInfo);
1314
1315                 RequestParameters requestParameters = new RequestParameters();
1316
1317                 // subscriptionServiceType
1318                 requestParameters.setSubscriptionServiceType("MOG");
1319
1320                 // Userparams
1321                 //List<E2EUserParam> userParams;
1322                 // userParams =
1323                 // e2eSir.getService().getParameters().getRequestParameters().getUserParams();
1324                 List<Map<String, Object>> userParamList = new ArrayList<>();
1325                 Map<String, Object> userParamMap = new HashMap<>();
1326                 // complete json request updated in the camunda
1327                 userParamMap.put("UUIRequest", requestJSON);
1328                 userParamMap.put("ServiceInstanceName", e2eSir.getService().getName());
1329
1330                 // Map<String, String> userParamMap3 = null;
1331                 // for (E2EUserParam userp : userParams) {
1332                 // userParamMap.put(userp.getName(), userp.getValue());
1333                 //
1334                 // }
1335                 userParamList.add(userParamMap);
1336                 requestParameters.setUserParams(userParamList);
1337
1338                 // setting requestParameters to requestDetails
1339                 requestDetails.setRequestParameters(requestParameters);
1340
1341                 sir.setRequestDetails(requestDetails);
1342
1343                 // converting to string
1344                 ObjectMapper mapper = new ObjectMapper();
1345                 try {
1346                         returnString = mapper.writeValueAsString(sir);
1347                 } catch (IOException e) {
1348                         msoLogger
1349                                         .debug("Exception while converting ServiceInstancesRequest object to string",
1350                                                         e);
1351                 }
1352
1353                 return returnString;
1354         }
1355
1356         private void createOperationStatusRecordForError(Action action,
1357                         String serviceId) throws MsoDatabaseException {
1358
1359                 AbstractSessionFactoryManager requestsDbSessionFactoryManager = new RequestsDbSessionFactoryManager();
1360
1361                 Session session = null;
1362                 try {
1363
1364                         session = requestsDbSessionFactoryManager.getSessionFactory()
1365                                         .openSession();
1366                         session.beginTransaction();
1367
1368                         OperationStatus os = new OperationStatus();
1369                         os.setOperation(action.name());
1370                         os.setOperationContent("");
1371                         os.setOperationId("");
1372                         os.setProgress("100");
1373                         os.setReason("");
1374                         os.setResult("error");
1375                         os.setServiceId(serviceId);
1376                         os.setUserId("");
1377                         Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
1378                         Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
1379                         os.setFinishedAt(endTimeStamp);
1380                         os.setOperateAt(startTimeStamp);
1381
1382                         session.save(os);
1383                         session.getTransaction().commit();
1384
1385                 } catch (Exception e) {
1386                         msoLogger.error(MessageEnum.APIH_DB_INSERT_EXC, "", "",
1387                                         MsoLogger.ErrorCode.DataError,
1388                                         "Exception when creation record request in Operation", e);
1389                         throw new MsoDatabaseException(
1390                                         "Data did inserted in Operatus Status Table for failure", e);
1391                 } finally {
1392                         if (null != session) {
1393                                 session.close();
1394                         }
1395                 }
1396         }
1397
1398         private void createOperationStatusRecord(String actionNm, String serviceId,
1399                         String operationId) throws MsoDatabaseException {
1400
1401                 AbstractSessionFactoryManager requestsDbSessionFactoryManager = new RequestsDbSessionFactoryManager();
1402
1403                 Session session = null;
1404                 try {
1405
1406                         session = requestsDbSessionFactoryManager.getSessionFactory()
1407                                         .openSession();
1408                         session.beginTransaction();
1409
1410                         OperationStatus os = new OperationStatus();
1411                         os.setOperation(actionNm);
1412                         os.setOperationContent("");
1413                         os.setOperationId(operationId);
1414                         os.setProgress("0");
1415                         os.setReason("");
1416                         os.setResult("processing");
1417                         os.setServiceId(serviceId);
1418                         // TODO : to be updated...
1419                         os.setUserId("");
1420                         Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
1421                         Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
1422                         os.setFinishedAt(endTimeStamp);
1423                         os.setOperateAt(startTimeStamp);
1424
1425                         session.save(os);
1426                         session.getTransaction().commit();
1427
1428                 } catch (Exception e) {
1429                         msoLogger.error(MessageEnum.APIH_DB_INSERT_EXC, "", "",
1430                                         MsoLogger.ErrorCode.DataError,
1431                                         "Exception when creation record request in Operation", e);
1432                         throw new MsoDatabaseException(
1433                                         "Data did inserted in Operatus Status Table", e);
1434                 } finally {
1435                         if (null != session) {
1436                                 session.close();
1437                         }
1438                 }
1439         }
1440
1441         private OperationStatus chkSvcInstOperStatusbySvcId(String serviceId) {
1442                 OperationStatus svcInstanceOperStatus = (RequestsDatabase.getInstance())
1443                                 .getOperationStatusByServiceId(serviceId);
1444
1445                 return svcInstanceOperStatus;
1446         }
1447
1448         private OperationStatus chkDuplicateServiceNameInOperStatus(
1449                         String serviceName) {
1450                 OperationStatus dupServiceName = (RequestsDatabase.getInstance())
1451                                 .getOperationStatusByServiceName(serviceName);
1452
1453                 return dupServiceName;
1454         }
1455 }