Quick fix to unblock the issue of VoLTE creation
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / E2EServiceInstances.java
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.POST;
33 import javax.ws.rs.Path;
34 import javax.ws.rs.PathParam;
35 import javax.ws.rs.Produces;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
38
39 import org.apache.http.HttpResponse;
40 import org.apache.http.HttpStatus;
41 import org.codehaus.jackson.map.ObjectMapper;
42 import org.hibernate.Session;
43
44 import org.openecomp.mso.apihandler.common.ErrorNumbers;
45 import org.openecomp.mso.apihandler.common.RequestClient;
46 import org.openecomp.mso.apihandler.common.RequestClientFactory;
47 import org.openecomp.mso.apihandler.common.ResponseHandler;
48 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceRequest;
49 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EUserParam;
50 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ModelInfo;
51 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestDetails;
52 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestInfo;
53 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestParameters;
54 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ServiceInstancesRequest;
55 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.SubscriberInfo;
56 import org.openecomp.mso.db.AbstractSessionFactoryManager;
57 import org.openecomp.mso.db.catalog.CatalogDatabase;
58 import org.openecomp.mso.db.catalog.beans.Service;
59 import org.openecomp.mso.db.catalog.beans.ServiceRecipe;
60 import org.openecomp.mso.logger.MessageEnum;
61 import org.openecomp.mso.logger.MsoAlarmLogger;
62 import org.openecomp.mso.logger.MsoLogger;
63 import org.openecomp.mso.requestsdb.InfraActiveRequests;
64 import org.openecomp.mso.requestsdb.OperationStatus;
65 import org.openecomp.mso.requestsdb.RequestsDatabase;
66 import org.openecomp.mso.requestsdb.RequestsDbSessionFactoryManager;
67 import org.openecomp.mso.utils.UUIDChecker;
68
69 import com.wordnik.swagger.annotations.Api;
70 import com.wordnik.swagger.annotations.ApiOperation;
71
72 @Path("/e2eServiceInstances")
73 @Api(value = "/e2eServiceInstances", description = "API Requests for E2E Service Instances")
74 public class E2EServiceInstances {
75
76         private HashMap<String, String> instanceIdMap = new HashMap<>();
77         private static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.APIH);
78         private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger();
79         public static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
80         private ServiceInstancesRequest sir = null;
81         
82         public static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: ";
83         public static final String EXCEPTION_CREATING_DB_RECORD = "Exception while creating record in DB";
84         public static final String EXCEPTION_COMMUNICATE_BPMN_ENGINE = "Exception while communicate with BPMN engine";
85
86         /**
87          * POST Requests for E2E Service create Instance on a version provided
88          */
89
90         @POST
91         @Path("/{version:[vV][3-5]}")
92         @Consumes(MediaType.APPLICATION_JSON)
93         @Produces(MediaType.APPLICATION_JSON)
94         @ApiOperation(value = "Create a E2E Service Instance on a version provided", response = Response.class)
95         public Response createE2EServiceInstance(String request, @PathParam("version") String version) {
96
97                 return processE2EserviceInstances(request, Action.createInstance, null, version);
98         }
99
100         /**
101          * DELETE Requests for E2E Service delete Instance on a specified version
102          * and serviceId
103          */
104
105         @DELETE
106         @Path("/{version:[vV][3-5]}/{serviceId}")
107         @Consumes(MediaType.APPLICATION_JSON)
108         @Produces(MediaType.APPLICATION_JSON)
109         @ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class)
110         public Response deleteE2EServiceInstance(String request, @PathParam("version") String version,
111                         @PathParam("serviceId") String serviceId) {
112
113                 instanceIdMap.put("serviceId", serviceId);
114
115                 return processE2EserviceInstances(request, Action.deleteInstance, null, version);
116         }
117
118         private Response processE2EserviceInstances(String requestJSON, Action action,
119                         HashMap<String, String> instanceIdMap, String version) {
120
121                 String requestId = UUIDChecker.generateUUID(msoLogger);
122                 long startTime = System.currentTimeMillis();
123                 msoLogger.debug("requestId is: " + requestId);
124                 E2EServiceInstanceRequest e2eSir = null;
125
126                 MsoRequest msoRequest = new MsoRequest(requestId);
127                 ObjectMapper mapper = new ObjectMapper();
128                 try {
129                         e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
130
131                 } catch (Exception e) {
132           //TODO update the service name
133           this.createOperationStatusRecordForError(action, requestId);
134                   
135                         msoLogger.debug("Mapping of request to JSON object failed : ", e);
136                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
137                                         MsoException.ServiceException, "Mapping of request to JSON object failed.  " + e.getMessage(),
138                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
139                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
140                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
141                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
142                                         "Mapping of request to JSON object failed");
143                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
144                         return response;
145                 }
146
147                 mapReqJsonToSvcInstReq(e2eSir, requestJSON);
148                 sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
149                 try {
150                         msoRequest.parse(sir, instanceIdMap, action, version);
151                 } catch (Exception e) {
152                         msoLogger.debug("Validation failed: ", e);
153                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
154                                         MsoException.ServiceException, "Error parsing request.  " + e.getMessage(),
155                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
156                         if (msoRequest.getRequestId() != null) {
157                                 msoLogger.debug("Logging failed message to the database");
158                                 //TODO update the service name
159                           this.createOperationStatusRecordForError(action, requestId);
160                         }
161                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
162                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
163                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
164                                         "Validation of the input request failed");
165                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
166                         return response;
167                 }
168
169                 InfraActiveRequests dup = null;
170 //              String instanceName = sir.getService().getName();
171 //              String requestScope = sir.getService().getParameters().getNodeType();
172                 String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
173                 String requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
174                 try {
175                         if (!(instanceName == null && "service".equals(requestScope)
176                                         && (action == Action.createInstance || action == Action.activateInstance))) {
177                           //TODO : Need to check for the duplicate record from the operation status,
178                           //TODO : commenting this check for unblocking current testing for now...  induces dead code...
179 //                              dup = (RequestsDatabase.getInstance()).checkInstanceNameDuplicate(instanceIdMap, instanceName,
180 //                                              requestScope);
181                         }
182                 } catch (Exception e) {
183                         msoLogger.error(MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "",
184                                         MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e);
185
186                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
187                                         MsoException.ServiceException, e.getMessage(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null);
188
189                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
190                                         "Error during duplicate check");
191                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
192                         return response;
193                 }
194
195                 if (dup != null) {
196                         // Found the duplicate record. Return the appropriate error.
197                         String instance = null;
198                         if (instanceName != null) {
199                                 instance = instanceName;
200                         } else {
201                                 instance = instanceIdMap.get(requestScope + "InstanceId");
202                         }
203                         String dupMessage = "Error: Locked instance - This " + requestScope + " (" + instance + ") "
204                                         + "already has a request being worked with a status of " + dup.getRequestStatus() + " (RequestId - "
205                                         + dup.getRequestId() + "). The existing request must finish or be cleaned up before proceeding.";
206
207                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT,
208                                         MsoException.ServiceException, dupMessage, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null);
209
210                         msoLogger.warn(MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError,
211                                         "Duplicate request - Subscriber already has a request for this service");
212                         
213                         createOperationStatusRecordForError(action, requestId);
214                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict,
215                                         dupMessage);
216                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
217                         return response;
218                 }
219                 
220                 CatalogDatabase db = null;
221                 RecipeLookupResult recipeLookupResult = null;
222                 try {
223                         db = CatalogDatabase.getInstance();
224                         recipeLookupResult = getServiceInstanceOrchestrationURI(db, action);
225                 } catch (Exception e) {
226                         msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "",
227                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
228                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
229                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
230                                         MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
231                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
232                         alarmLogger.sendAlarm("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL,
233                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
234                         createOperationStatusRecordForError(action, requestId);
235                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
236                                         "Exception while communciate with DB");
237                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
238                         return response;
239                 } finally {
240                         closeCatalogDB(db);
241                 }
242
243                 if (recipeLookupResult == null) {
244                         msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "",
245                                         MsoLogger.ErrorCode.DataError, "No recipe found in DB");
246                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
247                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
248                                         MsoException.ServiceException, "Recipe does not exist in catalog DB",
249                                         ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);
250                         createOperationStatusRecordForError(action, requestId);
251                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound,
252                                         "No recipe found in DB");
253                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
254
255                         return response;
256                 }
257
258 //              try {
259 //                      msoRequest.createRequestRecord(Status.PENDING, action);
260 //                      //createOperationStatusRecord(action, requestId);
261 //              } catch (Exception e) {
262 //                      msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC_REASON, "Exception while creating record in DB", "", "",
263 //                                      MsoLogger.ErrorCode.SchemaError, "Exception while creating record in DB", e);
264 //                      msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
265 //                      Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR,
266 //                                      MsoException.ServiceException, "Exception while creating record in DB " + e.getMessage(),
267 //                                      ErrorNumbers.SVC_BAD_PARAMETER, null);
268 //                      msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
269 //                                      "Exception while creating record in DB");
270 //                      msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
271 //                      return response;
272 //              }
273
274                 String serviceInstanceType = e2eSir.getService().getParameters().getServiceType();
275
276                 String serviceId = "";
277                 RequestClient requestClient = null;
278                 HttpResponse response = null;
279
280                 long subStartTime = System.currentTimeMillis();
281                 String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
282
283                 try {
284                         requestClient = RequestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI(),
285                                         MsoPropertiesUtils.loadMsoProperties());
286
287                         // Capture audit event
288                         msoLogger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
289
290                         response = requestClient.post(requestId, false, recipeLookupResult.getRecipeTimeout(), action.name(),
291                                         serviceId, null, null, null, null, serviceInstanceType, null, null, null, sirRequestJson);
292
293                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
294                                         "Successfully received response from BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI(),
295                                         null);
296                 } catch (Exception e) {
297                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.ERROR,
298                                         MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN",
299                                         recipeLookupResult.getOrchestrationURI(), null);
300                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
301                                         MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
302                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
303                         alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL,
304                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
305                         createOperationStatusRecordForError(action, requestId);
306                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
307                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
308                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError,
309                                         "Exception while communicate with BPMN engine");
310                         msoLogger.debug("End of the transaction, the final response is: " + (String) resp.getEntity());
311                         return resp;
312                 }
313
314                 if (response == null) {
315                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
316                                         MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
317                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
318                                         MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
319                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
320                                         "Null response from BPMN");
321                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity());
322                         return resp;
323                 }
324
325                 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
326                 int bpelStatus = respHandler.getStatus();
327
328                 return beplStatusUpdate(requestId, startTime, msoRequest, requestClient, respHandler, bpelStatus);
329         }
330
331         private void closeCatalogDB(CatalogDatabase db) {
332                 if (db != null) {
333                         db.close();
334                 }
335         }
336
337         private InfraActiveRequests checkForDuplicateRecord(Action action, HashMap<String, String> instanceIdMap,
338                         String instanceName, String requestScope) {
339                 InfraActiveRequests dupValue = null;
340                 if (!(instanceName == null && "service".equals(requestScope)
341                                 && (action == Action.createInstance || action == Action.activateInstance))) {
342                         dupValue = (RequestsDatabase.getInstance()).checkInstanceNameDuplicate(instanceIdMap, instanceName,
343                                         requestScope);
344                 }
345                 return dupValue;
346         }
347
348         private Response duplicateRecordFound(Action action, HashMap<String, String> instanceIdMap, long startTime,
349                         MsoRequest msoRequest, InfraActiveRequests dup, String instanceName, String requestScope) {
350                 String instance = null;
351                 if (instanceName != null) {
352                         instance = instanceName;
353                 } else {
354                         instance = instanceIdMap.get(requestScope + "InstanceId");
355                 }
356                 String dupMessage = "Error: Locked instance - This " + requestScope + " (" + instance + ") "
357                                 + "already has a request being worked with a status of " + dup.getRequestStatus() + " (RequestId - "
358                                 + dup.getRequestId() + "). The existing request must finish or be cleaned up before proceeding.";
359
360                 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, MsoException.ServiceException,
361                                 dupMessage, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null);
362
363                 msoLogger.warn(MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError,
364                                 "Duplicate request - Subscriber already has a request for this service");
365                 msoRequest.createRequestRecord(Status.FAILED, action);
366                 msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, dupMessage);
367                 msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
368                 return response;
369         }
370
371         private Response beplStatusUpdate(String requestId, long startTime, MsoRequest msoRequest,
372                         RequestClient requestClient, ResponseHandler respHandler, int bpelStatus) {
373                 // BPEL accepted the request, the request is in progress
374                 if (bpelStatus == HttpStatus.SC_ACCEPTED) {
375                         String camundaJSONResponseBody = respHandler.getResponseBody();
376                         msoLogger.debug("Received from Camunda: " + camundaJSONResponseBody);
377
378                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
379                                         "BPMN accepted the request, the request is in progress");
380                         msoLogger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody);
381                         return Response.status(HttpStatus.SC_ACCEPTED).entity(camundaJSONResponseBody).build();
382                 } else {
383                         List<String> variables = new ArrayList<>();
384                         variables.add(bpelStatus + "");
385                         String camundaJSONResponseBody = respHandler.getResponseBody();
386                         if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) {
387                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException,
388                                                 "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody,
389                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables);
390                                 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl(), "", "",
391                                                 MsoLogger.ErrorCode.BusinessProcesssError,
392                                                 "Response from BPEL engine is failed with HTTP Status=" + bpelStatus);
393                                 msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
394                                                 "Response from BPMN engine is failed");
395                                 msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity());
396                                 return resp;
397                         } else {
398                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException,
399                                                 "Request Failed due to BPEL error with HTTP Status= %1",
400                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables);
401                                 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl(), "", "",
402                                                 MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty");
403                                 msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
404                                                 "Response from BPEL engine is empty");
405                                 msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity());
406                                 return resp;
407                         }
408                 }
409         }
410
411         /**
412          * Getting recipes from catalogDb
413          * 
414          * @param db
415          * @param action
416          * @return
417          */
418         private RecipeLookupResult getServiceInstanceOrchestrationURI(CatalogDatabase db, Action action) {
419
420                 RecipeLookupResult recipeLookupResult = getServiceURI(db, action);
421
422                 if (recipeLookupResult != null) {
423                         msoLogger.debug("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI()
424                                         + ", recipe Timeout is: " + Integer.toString(recipeLookupResult.getRecipeTimeout()));
425                 } else {
426                         msoLogger.debug("No matching recipe record found");
427                 }
428                 return recipeLookupResult;
429         }
430
431         /**
432          * Getting recipes from catalogDb
433          * 
434          * @param db
435          * @param action
436          * @return
437          */
438         private RecipeLookupResult getServiceURI(CatalogDatabase db, Action action) {
439
440                 String defaultServiceModelName = "UUI_DEFAULT";
441
442                 Service serviceRecord = db.getServiceByModelName(defaultServiceModelName);
443                 ServiceRecipe recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name());
444
445                 if (recipe == null) {
446                         return null;
447                 }
448                 return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
449
450         }
451
452         /**
453          * Converting E2EServiceInstanceRequest to ServiceInstanceRequest and
454          * passing it to camunda engine.
455          * 
456          * @param e2eSir
457          * @return
458          */
459         private String mapReqJsonToSvcInstReq(E2EServiceInstanceRequest e2eSir, String requestJSON) {
460
461                 sir = new ServiceInstancesRequest();
462
463                 String returnString = null;
464                 RequestDetails requestDetails = new RequestDetails();
465                 ModelInfo modelInfo = new ModelInfo();
466
467                 // ModelInvariantId
468                 modelInfo.setModelInvariantId(e2eSir.getService().getServiceDefId());
469
470                 // modelNameVersionId
471                 modelInfo.setModelNameVersionId(e2eSir.getService().getTemplateId());
472
473 //              String modelInfoValue = e2eSir.getService().getParameters().getNodeTemplateName();
474 //              String[] arrayOfInfo = modelInfoValue.split(":");
475 //              String modelName = arrayOfInfo[0];
476 //              String modelVersion = arrayOfInfo[1];
477
478 //      TODO: To ensure, if we dont get the values from the UUI
479         String modelName = "voLTE";
480         String modelVersion = "1.0";
481                 // modelName
482                 modelInfo.setModelName(modelName);
483
484                 // modelVersion
485                 modelInfo.setModelVersion(modelVersion);
486
487                 // modelType
488                 modelInfo.setModelType(ModelType.service);
489
490                 // setting modelInfo to requestDetails
491                 requestDetails.setModelInfo(modelInfo);
492
493                 SubscriberInfo subscriberInfo = new SubscriberInfo();
494
495                 // globalsubscriberId
496                 subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getParameters().getGlobalSubscriberId());
497
498                 // subscriberName
499                 subscriberInfo.setSubscriberName(e2eSir.getService().getParameters().getSubscriberName());
500
501                 // setting subscriberInfo to requestDetails
502                 requestDetails.setSubscriberInfo(subscriberInfo);
503
504                 RequestInfo requestInfo = new RequestInfo();
505
506                 // instanceName
507                 requestInfo.setInstanceName(e2eSir.getService().getName());
508
509                 // source
510                 requestInfo.setSource("UUI");
511
512                 // suppressRollback
513                 requestInfo.setSuppressRollback(true);
514
515                 // setting requestInfo to requestDetails
516                 requestDetails.setRequestInfo(requestInfo);
517
518                 RequestParameters requestParameters = new RequestParameters();
519
520                 // subscriptionServiceType
521                 requestParameters.setSubscriptionServiceType("MOG");
522
523                 // Userparams
524                 List<E2EUserParam> userParams;
525                 //userParams = e2eSir.getService().getParameters().getRequestParameters().getUserParams();
526                 List<Map<String, String>> userParamList = new ArrayList<>();
527                 Map<String, String> userParamMap = new HashMap<>();
528                 //complete json request updated in the camunda
529                 userParamMap.put("UUIRequest", requestJSON);
530                 userParamMap.put("ServiceInstanceName", e2eSir.getService().getName());
531
532 //              Map<String, String> userParamMap3 = null;
533 //              for (E2EUserParam userp : userParams) {
534 //                      userParamMap.put(userp.getName(), userp.getValue());
535 //                      
536 //              }
537                 userParamList.add(userParamMap);
538                 requestParameters.setUserParams(userParamList);
539
540                 // setting requestParameters to requestDetails
541                 requestDetails.setRequestParameters(requestParameters);
542
543                 sir.setRequestDetails(requestDetails);
544
545                 // converting to string
546                 ObjectMapper mapper = new ObjectMapper();
547                 try {
548                         returnString = mapper.writeValueAsString(sir);
549                 } catch (IOException e) {
550                         msoLogger.debug("Exception while converting ServiceInstancesRequest object to string", e);
551                 }
552
553                 return returnString;
554         }
555
556         
557         private void createOperationStatusRecordForError(Action action, String requestId) {
558
559                         AbstractSessionFactoryManager requestsDbSessionFactoryManager = new RequestsDbSessionFactoryManager();
560
561                         Session session = null;
562                         try {
563
564                                 session = requestsDbSessionFactoryManager.getSessionFactory().openSession();
565                                 session.beginTransaction();
566                                 
567                           OperationStatus os = new OperationStatus();
568                           os.setOperation(action.name());
569                           os.setOperationContent("");
570                           os.setOperationId("");
571                           os.setProgress("100");
572                           os.setReason("");
573                           os.setResult("error");
574                           os.setServiceId(requestId);
575                           os.setUserId("");
576                           os.setFinishedAt(new Timestamp(System.currentTimeMillis()));
577                           os.setOperateAt(new Timestamp(System.currentTimeMillis()));
578
579                                 session.save(os);
580                                 session.getTransaction().commit();
581
582                         } catch (Exception e) {
583                                 msoLogger.error (MessageEnum.APIH_DB_INSERT_EXC, "", "", MsoLogger.ErrorCode.DataError, "Exception when creation record request in Operation", e);
584                         } finally {
585                                 if (null != session) {
586                                         session.close();
587                                 }
588                 }
589         }
590 }