Move pnfDefaultTimeout to dmaap.properties
[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.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.DELETE;
31 import javax.ws.rs.GET;
32 import javax.ws.rs.POST;
33 import javax.ws.rs.PUT;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.PathParam;
36 import javax.ws.rs.Produces;
37 import javax.ws.rs.core.MediaType;
38 import javax.ws.rs.core.Response;
39
40 import org.apache.http.HttpResponse;
41 import org.apache.http.HttpStatus;
42 import org.json.JSONObject;
43 import org.openecomp.mso.apihandler.common.ErrorNumbers;
44 import org.openecomp.mso.apihandler.common.RequestClient;
45 import org.openecomp.mso.apihandler.common.RequestClientFactory;
46 import org.openecomp.mso.apihandler.common.ResponseHandler;
47 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.CompareModelsRequest;
48 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceDeleteRequest;
49 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceRequest;
50 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceScaleRequest;
51 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.GetE2EServiceInstanceResponse;
52 import org.openecomp.mso.db.catalog.CatalogDatabase;
53 import org.openecomp.mso.db.catalog.beans.Service;
54 import org.openecomp.mso.db.catalog.beans.ServiceRecipe;
55 import org.openecomp.mso.logger.MessageEnum;
56 import org.openecomp.mso.logger.MsoAlarmLogger;
57 import org.openecomp.mso.logger.MsoLogger;
58 import org.openecomp.mso.requestsdb.OperationStatus;
59 import org.openecomp.mso.requestsdb.RequestsDatabase;
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.utils.UUIDChecker;
68
69 import com.fasterxml.jackson.databind.ObjectMapper;
70 import com.wordnik.swagger.annotations.Api;
71 import com.wordnik.swagger.annotations.ApiOperation;
72
73 @Path("/e2eServiceInstances")
74 @Api(value = "/e2eServiceInstances", description = "API Requests for E2E Service Instances")
75 public class E2EServiceInstances {
76
77         private HashMap<String, String> instanceIdMap = new HashMap<>();
78         private static MsoLogger msoLogger = MsoLogger
79                         .getMsoLogger(MsoLogger.Catalog.APIH);
80         private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger();
81         public static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
82         private ServiceInstancesRequest sir = null;
83
84         public static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: ";
85         public static final String EXCEPTION_CREATING_DB_RECORD = "Exception while creating record in DB";
86         public static final String EXCEPTION_COMMUNICATE_BPMN_ENGINE = "Exception while communicate with BPMN engine";
87
88         /**
89          * POST Requests for E2E Service create Instance on a version provided
90          */
91
92         @POST
93         @Path("/{version:[vV][3-5]}")
94         @Consumes(MediaType.APPLICATION_JSON)
95         @Produces(MediaType.APPLICATION_JSON)
96         @ApiOperation(value = "Create an E2E Service Instance on a version provided", response = Response.class)
97         public Response createE2EServiceInstance(String request,
98                         @PathParam("version") String version) {
99
100                 return processE2EserviceInstances(request, Action.createInstance, null,
101                                 version);
102         }
103         
104         /**
105          * PUT Requests for E2E Service update Instance on a version provided
106          */
107
108         @PUT
109         @Path("/{version:[vV][3-5]}/{serviceId}")
110         @Consumes(MediaType.APPLICATION_JSON)
111         @Produces(MediaType.APPLICATION_JSON)
112         @ApiOperation(value = "Update an E2E Service Instance on a version provided and serviceId", response = Response.class)
113         public Response updateE2EServiceInstance(String request,
114                         @PathParam("version") String version,
115                         @PathParam("serviceId") String serviceId) {
116                 
117                 instanceIdMap.put("serviceId", serviceId);
118
119                 return updateE2EserviceInstances(request, Action.updateInstance, instanceIdMap,
120                                 version);
121         }
122
123         /**
124          * DELETE Requests for E2E Service delete Instance on a specified version
125          * and serviceId
126          */
127
128         @DELETE
129         @Path("/{version:[vV][3-5]}/{serviceId}")
130         @Consumes(MediaType.APPLICATION_JSON)
131         @Produces(MediaType.APPLICATION_JSON)
132         @ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class)
133         public Response deleteE2EServiceInstance(String request,
134                         @PathParam("version") String version,
135                         @PathParam("serviceId") String serviceId) {
136
137                 instanceIdMap.put("serviceId", serviceId);
138
139                 return deleteE2EserviceInstances(request, Action.deleteInstance,
140                                 instanceIdMap, version);
141         }
142
143         @GET
144         @Path("/{version:[vV][3-5]}/{serviceId}/operations/{operationId}")
145         @ApiOperation(value = "Find e2eServiceInstances Requests for a given serviceId and operationId", response = Response.class)
146         @Produces(MediaType.APPLICATION_JSON)
147         public Response getE2EServiceInstances(
148                         @PathParam("serviceId") String serviceId,
149                         @PathParam("version") String version,
150                         @PathParam("operationId") String operationId) {
151                 return getE2EServiceInstances(serviceId, operationId);
152         }
153         
154     /**
155          * Scale Requests for E2E Service scale Instance on a specified version 
156      */
157          
158         @POST
159         @Path("/{version:[vV][3-5]}/{serviceId}/scale")
160         @Consumes(MediaType.APPLICATION_JSON)
161         @Produces(MediaType.APPLICATION_JSON)
162         @ApiOperation(value="Scale E2E Service Instance on a specified version",response=Response.class)
163         public Response scaleE2EServiceInstance(String request,
164                                             @PathParam("version") String version,
165                                             @PathParam("serviceId") String serviceId) {
166
167                 msoLogger.debug("------------------scale begin------------------");
168                 instanceIdMap.put("serviceId", serviceId);
169                 return scaleE2EserviceInstances(request, Action.scaleInstance, instanceIdMap, version);
170         }
171         /**
172          * GET Requests for Comparing model of service instance with target version
173          */
174         
175         @POST
176         @Path("/{version:[vV][3-5]}/{serviceId}/modeldifferences")
177         @Consumes(MediaType.APPLICATION_JSON)
178         @Produces(MediaType.APPLICATION_JSON)
179         @ApiOperation(value = "Find added and deleted resources of target model for the e2eserviceInstance on a given serviceId ", response = Response.class)
180         public Response compareModelwithTargetVersion(String request,
181                         @PathParam("serviceId") String serviceId,
182                         @PathParam("version") String version) {
183                 
184                 instanceIdMap.put("serviceId", serviceId);
185                 
186                 return compareModelwithTargetVersion(request, Action.compareModel, instanceIdMap, version);
187         }       
188
189         private Response compareModelwithTargetVersion(String requestJSON, Action action,
190                         HashMap<String, String> instanceIdMap, String version) {
191
192                 String requestId = UUIDChecker.generateUUID(msoLogger);
193                 long startTime = System.currentTimeMillis();
194                 msoLogger.debug("requestId is: " + requestId);
195
196                 CompareModelsRequest e2eCompareModelReq = null;
197
198                 MsoRequest msoRequest = new MsoRequest(requestId);
199
200                 ObjectMapper mapper = new ObjectMapper();
201                 try {
202                         e2eCompareModelReq = mapper.readValue(requestJSON, CompareModelsRequest.class);
203
204                 } catch (Exception e) {
205
206                         msoLogger.debug("Mapping of request to JSON object failed : ", e);
207                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
208                                         MsoException.ServiceException, "Mapping of request to JSON object failed.  " + e.getMessage(),
209                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
210                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
211                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
212                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
213                                         "Mapping of request to JSON object failed");
214                         msoLogger.debug("End of the transaction, the final response is: " + response.getEntity().toString());
215
216                         return response;
217                 }
218
219                 Response returnResp = runCompareModelBPMWorkflow(e2eCompareModelReq, msoRequest, requestJSON, requestId,
220                                 startTime, action);
221
222                 return returnResp;
223
224         }
225
226         private Response runCompareModelBPMWorkflow(CompareModelsRequest e2eCompareModelReq, MsoRequest msoRequest,
227                         String requestJSON, String requestId, long startTime, Action action) {
228                 
229                 // Define RecipeLookupResult info here instead of query DB for efficiency
230                 String workflowUrl = "/mso/async/services/CompareModelofE2EServiceInstance";
231                 int recipeTimeout = 180;
232
233                 RequestClient requestClient = null;
234                 HttpResponse response = null;
235
236                 long subStartTime = System.currentTimeMillis();
237
238                 try {
239                         requestClient = RequestClientFactory.getRequestClient(workflowUrl, MsoPropertiesUtils.loadMsoProperties());
240
241                         JSONObject jjo = new JSONObject(requestJSON);
242                         String bpmnRequest = jjo.toString();
243
244                         // Capture audit event
245                         msoLogger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
246                         String serviceId = instanceIdMap.get("serviceId");
247                         String serviceType = e2eCompareModelReq.getServiceType();
248                         response = requestClient.post(requestId, false, recipeTimeout, action.name(), serviceId, null, null, null,
249                                         null, null, serviceType, null, null, null, bpmnRequest, null);
250
251                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
252                                         "Successfully received response from BPMN engine", "BPMN", workflowUrl, null);
253                 } catch (Exception e) {
254                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.ERROR,
255                                         MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN",
256                                         workflowUrl, null);
257                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
258                                         MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
259                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
260                         alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL,
261                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
262                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
263                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine",e);
264                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError,
265                                         "Exception while communicate with BPMN engine");
266                         msoLogger.debug("End of the transaction, the final response is: " + resp.getEntity().toString());
267                         return resp;
268                 }
269
270                 if (response == null) {
271                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
272                                         MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
273                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
274                                         MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
275                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
276                                         "Null response from BPMN");
277                         msoLogger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString());
278                         return resp;
279                 }
280
281                 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
282                 int bpelStatus = respHandler.getStatus();
283                 // String responseBody = respHandler.getResponseBody();
284                 // CompareModelsResult modelDiffResponse = new CompareModelsResult();
285
286                 return beplStatusUpdate(requestId, startTime, msoRequest, requestClient, respHandler, bpelStatus, action,
287                                 instanceIdMap);
288         }
289
290         private Response getE2EServiceInstances(String serviceId, String operationId) {
291                 RequestsDatabase requestsDB = RequestsDatabase.getInstance();
292
293                 GetE2EServiceInstanceResponse e2eServiceResponse = new GetE2EServiceInstanceResponse();
294
295                 MsoRequest msoRequest = new MsoRequest(serviceId);
296
297                 long startTime = System.currentTimeMillis();
298
299                 OperationStatus operationStatus = null;
300
301                 try {
302                         operationStatus = requestsDB.getOperationStatus(serviceId,
303                                         operationId);
304
305                 } catch (Exception e) {
306                         msoLogger
307                                         .error(MessageEnum.APIH_DB_ACCESS_EXC,
308                                                         MSO_PROP_APIHANDLER_INFRA,
309                                                         "",
310                                                         "",
311                                                         MsoLogger.ErrorCode.AvailabilityError,
312                                                         "Exception while communciate with Request DB - Infra Request Lookup",
313                                                         e);
314                         msoRequest
315                                         .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
316                         Response response = msoRequest.buildServiceErrorResponse(
317                                         HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
318                                         e.getMessage(),
319                                         ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null);
320                         alarmLogger.sendAlarm("MsoDatabaseAccessError",
321                                         MsoAlarmLogger.CRITICAL, Messages.errors
322                                                         .get(ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB));
323                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
324                                         MsoLogger.ResponseCode.DBAccessError,
325                                         "Exception while communciate with Request DB");
326                         msoLogger.debug("End of the transaction, the final response is: "
327                                         + (String) response.getEntity());
328                         return response;
329
330                 }
331
332                 if (operationStatus == null) {
333                         Response resp = msoRequest.buildServiceErrorResponse(
334                                         HttpStatus.SC_NO_CONTENT, MsoException.ServiceException,
335                                         "E2E serviceId " + serviceId + " is not found in DB",
336                                         ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null);
337                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
338                                         MSO_PROP_APIHANDLER_INFRA, "", "",
339                                         MsoLogger.ErrorCode.BusinessProcesssError,
340                                         "Null response from RequestDB when searching by serviceId");
341                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
342                                         MsoLogger.ResponseCode.DataNotFound,
343                                         "Null response from RequestDB when searching by serviceId");
344                         msoLogger.debug("End of the transaction, the final response is: "
345                                         + (String) resp.getEntity());
346                         return resp;
347
348                 }
349
350                 e2eServiceResponse.setOperationStatus(operationStatus);
351
352                 return Response.status(200).entity(e2eServiceResponse).build();
353         }
354
355         private Response deleteE2EserviceInstances(String requestJSON,
356                         Action action, HashMap<String, String> instanceIdMap, String version) {
357                 // TODO should be a new one or the same service instance Id
358                 String requestId = UUIDChecker.generateUUID(msoLogger);
359                 long startTime = System.currentTimeMillis();
360                 msoLogger.debug("requestId is: " + requestId);
361                 E2EServiceInstanceDeleteRequest e2eDelReq = null;
362
363                 MsoRequest msoRequest = new MsoRequest(requestId);
364
365                 ObjectMapper mapper = new ObjectMapper();
366                 try {
367                         e2eDelReq = mapper.readValue(requestJSON,
368                                         E2EServiceInstanceDeleteRequest.class);
369
370                 } catch (Exception e) {
371
372                         msoLogger.debug("Mapping of request to JSON object failed : ", e);
373                         Response response = msoRequest.buildServiceErrorResponse(
374                                         HttpStatus.SC_BAD_REQUEST,
375                                         MsoException.ServiceException,
376                                         "Mapping of request to JSON object failed.  "
377                                                         + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER,
378                                         null);
379                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
380                                         MSO_PROP_APIHANDLER_INFRA, "", "",
381                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
382                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
383                                         MsoLogger.ResponseCode.SchemaError,
384                                         "Mapping of request to JSON object failed");
385                         msoLogger.debug("End of the transaction, the final response is: "
386                                         + (String) response.getEntity());
387                         return response;
388                 }
389
390                 CatalogDatabase db = null;
391                 RecipeLookupResult recipeLookupResult = null;
392                 try {
393                         db = CatalogDatabase.getInstance();
394                         //TODO  Get the service template model version uuid from AAI.
395                         recipeLookupResult = getServiceInstanceOrchestrationURI(db, null, action);
396                 } catch (Exception e) {
397                         msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC,
398                                         MSO_PROP_APIHANDLER_INFRA, "", "",
399                                         MsoLogger.ErrorCode.AvailabilityError,
400                                         "Exception while communciate with Catalog DB", e);
401                         msoRequest
402                                         .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
403                         Response response = msoRequest.buildServiceErrorResponse(
404                                         HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
405                                         "No communication to catalog DB " + e.getMessage(),
406                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
407                         alarmLogger.sendAlarm("MsoDatabaseAccessError",
408                                         MsoAlarmLogger.CRITICAL, Messages.errors
409                                                         .get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
410                         msoRequest.createRequestRecord(Status.FAILED, action);
411                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
412                                         MsoLogger.ResponseCode.DBAccessError,
413                                         "Exception while communciate with DB");
414                         msoLogger.debug(END_OF_THE_TRANSACTION
415                                         + (String) response.getEntity());
416                         return response;
417                 } finally {
418                         closeCatalogDB(db);
419                 }
420                 if (recipeLookupResult == null) {
421                         msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
422                                         MSO_PROP_APIHANDLER_INFRA, "", "",
423                                         MsoLogger.ErrorCode.DataError, "No recipe found in DB");
424                         msoRequest
425                                         .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
426                         Response response = msoRequest.buildServiceErrorResponse(
427                                         HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
428                                         "Recipe does not exist in catalog DB",
429                                         ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);
430                         msoRequest.createRequestRecord(Status.FAILED, action);
431                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
432                                         MsoLogger.ResponseCode.DataNotFound,
433                                         "No recipe found in DB");
434                         msoLogger.debug(END_OF_THE_TRANSACTION
435                                         + (String) response.getEntity());
436                         return response;
437                 }
438
439                 RequestClient requestClient = null;
440                 HttpResponse response = null;
441
442                 long subStartTime = System.currentTimeMillis();
443                 // String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
444
445                 try {
446                         requestClient = RequestClientFactory.getRequestClient(
447                                         recipeLookupResult.getOrchestrationURI(),
448                                         MsoPropertiesUtils.loadMsoProperties());
449
450                         JSONObject jjo = new JSONObject(requestJSON);
451                         jjo.put("operationId", UUIDChecker.generateUUID(msoLogger));
452
453                         String bpmnRequest = jjo.toString();
454
455                         // Capture audit event
456                         msoLogger
457                                         .debug("MSO API Handler Posting call to BPEL engine for url: "
458                                                         + requestClient.getUrl());
459                         String serviceId = instanceIdMap.get("serviceId");
460                         String serviceInstanceType = e2eDelReq.getServiceType();
461                         response = requestClient.post(requestId, false,
462                                         recipeLookupResult.getRecipeTimeout(), action.name(),
463                                         serviceId, null, null, null, null, null, serviceInstanceType,
464                                         null, null, null, bpmnRequest, recipeLookupResult.getRecipeParamXsd());
465
466                         msoLogger.recordMetricEvent(subStartTime,
467                                         MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
468                                         "Successfully received response from BPMN engine", "BPMN",
469                                         recipeLookupResult.getOrchestrationURI(), null);
470                 } catch (Exception e) {
471                         msoLogger.recordMetricEvent(subStartTime,
472                                         MsoLogger.StatusCode.ERROR,
473                                         MsoLogger.ResponseCode.CommunicationError,
474                                         "Exception while communicate with BPMN engine", "BPMN",
475                                         recipeLookupResult.getOrchestrationURI(), null);
476                         Response resp = msoRequest.buildServiceErrorResponse(
477                                         HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
478                                         "Failed calling bpmn " + e.getMessage(),
479                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
480                         alarmLogger.sendAlarm("MsoConfigurationError",
481                                         MsoAlarmLogger.CRITICAL,
482                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
483                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
484                                         MSO_PROP_APIHANDLER_INFRA, "", "",
485                                         MsoLogger.ErrorCode.AvailabilityError,
486                                         "Exception while communicate with BPMN engine");
487                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
488                                         MsoLogger.ResponseCode.CommunicationError,
489                                         "Exception while communicate with BPMN engine");
490                         msoLogger.debug("End of the transaction, the final response is: "
491                                         + (String) resp.getEntity());
492                         return resp;
493                 }
494
495                 if (response == null) {
496                         Response resp = msoRequest.buildServiceErrorResponse(
497                                         HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
498                                         "bpelResponse is null",
499                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
500                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
501                                         MSO_PROP_APIHANDLER_INFRA, "", "",
502                                         MsoLogger.ErrorCode.BusinessProcesssError,
503                                         "Null response from BPEL");
504                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
505                                         MsoLogger.ResponseCode.InternalError,
506                                         "Null response from BPMN");
507                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity());
508                         return resp;
509                 }
510
511                 ResponseHandler respHandler = new ResponseHandler(response,
512                                 requestClient.getType());
513                 int bpelStatus = respHandler.getStatus();
514
515                 return beplStatusUpdate(requestId, startTime, msoRequest,
516                                 requestClient, respHandler, bpelStatus, action, instanceIdMap);
517         }
518
519         private Response updateE2EserviceInstances(String requestJSON, Action action,
520                         HashMap<String, String> instanceIdMap, String version) {
521
522                 String requestId = UUIDChecker.generateUUID(msoLogger);
523                 long startTime = System.currentTimeMillis();
524                 msoLogger.debug("requestId is: " + requestId);
525                 E2EServiceInstanceRequest e2eSir = null;
526                 String serviceId = instanceIdMap.get("serviceId");
527
528                 MsoRequest msoRequest = new MsoRequest(requestId);
529                 ObjectMapper mapper = new ObjectMapper();
530                 try {
531                         e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
532
533                 } catch (Exception e) {
534           
535                         msoLogger.debug("Mapping of request to JSON object failed : ", e);
536                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
537                                         MsoException.ServiceException, "Mapping of request to JSON object failed.  " + e.getMessage(),
538                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
539                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
540                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
541                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
542                                         "Mapping of request to JSON object failed");
543                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
544                         return response;
545                 }
546
547                 mapReqJsonToSvcInstReq(e2eSir, requestJSON);
548                 sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
549                 try {
550                         msoRequest.parse(sir, instanceIdMap, action, version, requestJSON);
551                 } catch (Exception e) {
552                         msoLogger.debug("Validation failed: ", e);
553                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
554                                         MsoException.ServiceException, "Error parsing request.  " + e.getMessage(),
555                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
556                         if (msoRequest.getRequestId() != null) {
557                                 msoLogger.debug("Logging failed message to the database");
558                         }
559                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
560                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
561                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
562                                         "Validation of the input request failed");
563                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
564                         return response;
565                 }
566                 
567                 //check for the current operation status
568 //              Response resp = checkE2ESvcInstStatus(action, serviceId, startTime, msoRequest);
569 //              if(resp != null && resp.getStatus() != 200) {
570 //                      return resp;
571 //              }
572                 
573                 CatalogDatabase db = null;
574                 RecipeLookupResult recipeLookupResult = null;
575                 try {
576                         db = CatalogDatabase.getInstance();
577                         recipeLookupResult = getServiceInstanceOrchestrationURI(db, e2eSir.getService().getServiceUuid(), action);
578                 } catch (Exception e) {
579                         msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "",
580                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
581                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
582                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
583                                         MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
584                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
585                         alarmLogger.sendAlarm("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL,
586                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
587                         
588                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
589                                         "Exception while communciate with DB");
590                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
591                         
592                         return response;
593                 } finally {
594                         closeCatalogDB(db);
595                 }
596
597                 if (recipeLookupResult == null) {
598                         msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "",
599                                         MsoLogger.ErrorCode.DataError, "No recipe found in DB");
600                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
601                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
602                                         MsoException.ServiceException, "Recipe does not exist in catalog DB",
603                                         ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);
604                 
605                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound,
606                                         "No recipe found in DB");
607                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
608
609                         return response;
610                 }
611
612                 String serviceInstanceType = e2eSir.getService().getServiceType();
613
614                 RequestClient requestClient = null;
615                 HttpResponse response = null;
616
617                 long subStartTime = System.currentTimeMillis();
618                 String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
619
620                 try {
621                         requestClient = RequestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI(),
622                                         MsoPropertiesUtils.loadMsoProperties());
623
624                         // Capture audit event
625                         msoLogger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
626
627                         response = requestClient.post(requestId, false, recipeLookupResult.getRecipeTimeout(), action.name(),
628                                         serviceId, null, null, null, null, null, serviceInstanceType, null, null, null, sirRequestJson,
629                                         recipeLookupResult.getRecipeParamXsd());
630
631                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
632                                         "Successfully received response from BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI(),
633                                         null);
634                 } catch (Exception e) {
635                         msoLogger.debug("Exception while communicate with BPMN engine", e);
636                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.ERROR,
637                                         MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN",
638                                         recipeLookupResult.getOrchestrationURI(), null);
639                         Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
640                                         MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
641                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
642                         alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL,
643                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
644                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
645                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
646                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError,
647                                         "Exception while communicate with BPMN engine");
648                         msoLogger.debug("End of the transaction, the final response is: " + (String) getBPMNResp.getEntity());
649
650                         return getBPMNResp;
651                 }
652
653                 if (response == null) {
654                         Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
655                                         MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
656                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
657                                         MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
658                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
659                                         "Null response from BPMN");
660                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) getBPMNResp.getEntity());
661
662                         return getBPMNResp;
663                 }
664
665                 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
666                 int bpelStatus = respHandler.getStatus();
667
668                 return beplStatusUpdate(serviceId, startTime, msoRequest, requestClient, respHandler, bpelStatus, action, instanceIdMap);
669         }
670
671         private Response processE2EserviceInstances(String requestJSON, Action action,
672                         HashMap<String, String> instanceIdMap, String version) {
673
674                 String requestId = UUIDChecker.generateUUID(msoLogger);
675                 long startTime = System.currentTimeMillis();
676                 msoLogger.debug("requestId is: " + requestId);
677                 E2EServiceInstanceRequest e2eSir = null;
678
679                 MsoRequest msoRequest = new MsoRequest(requestId);
680                 ObjectMapper mapper = new ObjectMapper();
681                 try {
682                         e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
683
684                 } catch (Exception e) {
685           
686                         msoLogger.debug("Mapping of request to JSON object failed : ", e);
687                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
688                                         MsoException.ServiceException, "Mapping of request to JSON object failed.  " + e.getMessage(),
689                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
690                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
691                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
692                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
693                                         "Mapping of request to JSON object failed");
694                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
695                         return response;
696                 }
697
698                 mapReqJsonToSvcInstReq(e2eSir, requestJSON);
699                 sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
700                 try {
701                         msoRequest.parse(sir, instanceIdMap, action, version, requestJSON);
702                 } catch (Exception e) {
703                         msoLogger.debug("Validation failed: ", e);
704                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
705                                         MsoException.ServiceException, "Error parsing request.  " + e.getMessage(),
706                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
707                         if (msoRequest.getRequestId() != null) {
708                                 msoLogger.debug("Logging failed message to the database");
709                         }
710                         msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
711                                         MsoLogger.ErrorCode.SchemaError, requestJSON, e);
712                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError,
713                                         "Validation of the input request failed");
714                         msoLogger.debug("End of the transaction, the final response is: " + (String) response.getEntity());
715                         return response;
716                 }               
717
718                 CatalogDatabase db = null;
719                 RecipeLookupResult recipeLookupResult = null;
720                 try {
721                         db = CatalogDatabase.getInstance();
722                         recipeLookupResult = getServiceInstanceOrchestrationURI(db, e2eSir.getService().getServiceUuid(), action);
723                 } catch (Exception e) {
724                         msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "",
725                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
726                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
727                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
728                                         MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
729                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
730                         alarmLogger.sendAlarm("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL,
731                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
732                         
733                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError,
734                                         "Exception while communciate with DB");
735                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
736                         return response;
737                 } finally {
738                         closeCatalogDB(db);
739                 }
740
741                 if (recipeLookupResult == null) {
742                         msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "",
743                                         MsoLogger.ErrorCode.DataError, "No recipe found in DB");
744                         msoRequest.setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
745                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
746                                         MsoException.ServiceException, "Recipe does not exist in catalog DB",
747                                         ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);
748                 
749                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound,
750                                         "No recipe found in DB");
751                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) response.getEntity());
752                         return response;
753                 }
754
755                 String serviceInstanceType = e2eSir.getService().getServiceType();
756
757                 String serviceId = "";
758                 RequestClient requestClient = null;
759                 HttpResponse response = null;
760
761                 long subStartTime = System.currentTimeMillis();
762                 String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
763
764                 try {
765                         requestClient = RequestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI(),
766                                         MsoPropertiesUtils.loadMsoProperties());
767
768                         // Capture audit event
769                         msoLogger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
770
771                         response = requestClient.post(requestId, false, recipeLookupResult.getRecipeTimeout(), action.name(),
772                                         serviceId, null, null, null, null, null, serviceInstanceType, null, null, null, sirRequestJson,
773                                         recipeLookupResult.getRecipeParamXsd());
774
775                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
776                                         "Successfully received response from BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI(),
777                                         null);
778                 } catch (Exception e) {
779                         msoLogger.recordMetricEvent(subStartTime, MsoLogger.StatusCode.ERROR,
780                                         MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN",
781                                         recipeLookupResult.getOrchestrationURI(), null);
782                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
783                                         MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
784                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
785                         alarmLogger.sendAlarm("MsoConfigurationError", MsoAlarmLogger.CRITICAL,
786                                         Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
787                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
788                                         MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
789                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError,
790                                         "Exception while communicate with BPMN engine");
791                         msoLogger.debug("End of the transaction, the final response is: " + (String) resp.getEntity());
792                         return resp;
793                 }
794
795                 if (response == null) {
796                         Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
797                                         MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
798                         msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
799                                         MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
800                         msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError,
801                                         "Null response from BPMN");
802                         msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity());
803                         return resp;
804                 }
805
806                 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
807                 int bpelStatus = respHandler.getStatus();
808
809                 return beplStatusUpdate(requestId, startTime, msoRequest, requestClient, respHandler, bpelStatus, action, instanceIdMap);
810         }
811
812    private Response scaleE2EserviceInstances(String requestJSON,
813                                                Action action, HashMap<String, String> instanceIdMap, String version) {
814
815         String requestId = UUIDChecker.generateUUID(msoLogger);
816         long startTime = System.currentTimeMillis();
817         msoLogger.debug("requestId is: " + requestId);
818                 E2EServiceInstanceScaleRequest e2eScaleReq = null;
819
820         MsoRequest msoRequest = new MsoRequest(requestId);
821
822         ObjectMapper mapper = new ObjectMapper();
823         try {
824                 e2eScaleReq = mapper.readValue(requestJSON,
825                                         E2EServiceInstanceScaleRequest.class);
826
827         } catch (Exception e) {
828
829             msoLogger.debug("Mapping of request to JSON object failed : ", e);
830             Response response = msoRequest.buildServiceErrorResponse(
831                     HttpStatus.SC_BAD_REQUEST,
832                     MsoException.ServiceException,
833                     "Mapping of request to JSON object failed.  "
834                             + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER,
835                     null);
836             msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
837                     MSO_PROP_APIHANDLER_INFRA, "", "",
838                     MsoLogger.ErrorCode.SchemaError, requestJSON, e);
839             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
840                     MsoLogger.ResponseCode.SchemaError,
841                     "Mapping of request to JSON object failed");
842             msoLogger.debug("End of the transaction, the final response is: "
843                     + (String) response.getEntity());
844             return response;
845         }
846
847         CatalogDatabase db = null;
848         RecipeLookupResult recipeLookupResult = null;
849         try {
850             db = CatalogDatabase.getInstance();
851                         //TODO  Get the service template model version uuid from AAI.
852                         recipeLookupResult = getServiceInstanceOrchestrationURI(db, null, action);
853         } catch (Exception e) {
854             msoLogger.error(MessageEnum.APIH_DB_ACCESS_EXC,
855                     MSO_PROP_APIHANDLER_INFRA, "", "",
856                     MsoLogger.ErrorCode.AvailabilityError,
857                     "Exception while communciate with Catalog DB", e);
858             msoRequest
859                     .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
860             Response response = msoRequest.buildServiceErrorResponse(
861                     HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
862                     "No communication to catalog DB " + e.getMessage(),
863                     ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
864             alarmLogger.sendAlarm("MsoDatabaseAccessError",
865                     MsoAlarmLogger.CRITICAL, Messages.errors
866                             .get(ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
867             msoRequest.createRequestRecord(Status.FAILED, action);
868             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
869                     MsoLogger.ResponseCode.DBAccessError,
870                     "Exception while communciate with DB");
871             msoLogger.debug(END_OF_THE_TRANSACTION
872                     + (String) response.getEntity());
873             return response;
874         } finally {
875             closeCatalogDB(db);
876         }
877         if (recipeLookupResult == null) {
878             msoLogger.error(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
879                     MSO_PROP_APIHANDLER_INFRA, "", "",
880                     MsoLogger.ErrorCode.DataError, "No recipe found in DB");
881             msoRequest
882                     .setStatus(org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
883             Response response = msoRequest.buildServiceErrorResponse(
884                     HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
885                     "Recipe does not exist in catalog DB",
886                     ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null);
887             msoRequest.createRequestRecord(Status.FAILED, action);
888             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
889                     MsoLogger.ResponseCode.DataNotFound,
890                     "No recipe found in DB");
891             msoLogger.debug(END_OF_THE_TRANSACTION
892                     + (String) response.getEntity());
893             return response;
894         }
895
896         RequestClient requestClient = null;
897         HttpResponse response = null;
898
899         long subStartTime = System.currentTimeMillis();
900         // String sirRequestJson = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
901
902         try {
903             requestClient = RequestClientFactory.getRequestClient(
904                     recipeLookupResult.getOrchestrationURI(),
905                     MsoPropertiesUtils.loadMsoProperties());
906
907             JSONObject jjo = new JSONObject(requestJSON);
908             jjo.put("operationId", UUIDChecker.generateUUID(msoLogger));
909
910             String bpmnRequest = jjo.toString();
911
912             // Capture audit event
913             msoLogger
914                     .debug("MSO API Handler Posting call to BPEL engine for url: "
915                             + requestClient.getUrl());
916             String serviceId = instanceIdMap.get("serviceId");
917             String serviceInstanceType = e2eScaleReq.getService().getServiceType();
918             response = requestClient.post(requestId, false,
919                                         recipeLookupResult.getRecipeTimeout(), action.name(),
920                                         serviceId, null, null, null, null, null, serviceInstanceType,
921                                         null, null, null, bpmnRequest, recipeLookupResult.getRecipeParamXsd());
922
923             msoLogger.recordMetricEvent(subStartTime,
924                     MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
925                     "Successfully received response from BPMN engine", "BPMN",
926                     recipeLookupResult.getOrchestrationURI(), null);
927         } catch (Exception e) {
928             msoLogger.recordMetricEvent(subStartTime,
929                     MsoLogger.StatusCode.ERROR,
930                     MsoLogger.ResponseCode.CommunicationError,
931                     "Exception while communicate with BPMN engine", "BPMN",
932                     recipeLookupResult.getOrchestrationURI(), null);
933             Response resp = msoRequest.buildServiceErrorResponse(
934                     HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
935                     "Failed calling bpmn " + e.getMessage(),
936                     ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
937             alarmLogger.sendAlarm("MsoConfigurationError",
938                     MsoAlarmLogger.CRITICAL,
939                     Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
940             msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
941                     MSO_PROP_APIHANDLER_INFRA, "", "",
942                     MsoLogger.ErrorCode.AvailabilityError,
943                     "Exception while communicate with BPMN engine",e);
944             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
945                     MsoLogger.ResponseCode.CommunicationError,
946                     "Exception while communicate with BPMN engine");
947             msoLogger.debug("End of the transaction, the final response is: "
948                     + (String) resp.getEntity());
949             return resp;
950         }
951
952         if (response == null) {
953             Response resp = msoRequest.buildServiceErrorResponse(
954                     HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
955                     "bpelResponse is null",
956                     ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
957             msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
958                     MSO_PROP_APIHANDLER_INFRA, "", "",
959                     MsoLogger.ErrorCode.BusinessProcesssError,
960                     "Null response from BPEL");
961             msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
962                     MsoLogger.ResponseCode.InternalError,
963                     "Null response from BPMN");
964             msoLogger.debug(END_OF_THE_TRANSACTION + (String) resp.getEntity());
965             return resp;
966         }
967
968         ResponseHandler respHandler = new ResponseHandler(response,
969                 requestClient.getType());
970         int bpelStatus = respHandler.getStatus();
971
972         return beplStatusUpdate(requestId, startTime, msoRequest,
973                 requestClient, respHandler, bpelStatus, action, instanceIdMap);
974     }
975
976         private void closeCatalogDB(CatalogDatabase db) {
977                 if (db != null) {
978                         db.close();
979                 }
980         }
981
982         private Response beplStatusUpdate(String serviceId, long startTime,
983                         MsoRequest msoRequest, RequestClient requestClient,
984                         ResponseHandler respHandler, int bpelStatus, Action action,
985                         HashMap<String, String> instanceIdMap) {
986                 // BPMN accepted the request, the request is in progress
987                 if (bpelStatus == HttpStatus.SC_ACCEPTED) {
988                         String camundaJSONResponseBody = respHandler.getContent();
989                         msoLogger.debug("Received from Camunda: " + camundaJSONResponseBody);
990                         msoLogger.recordAuditEvent(startTime,
991                                         MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
992                                         "BPMN accepted the request, the request is in progress");
993                         msoLogger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody);
994                         return Response.status(HttpStatus.SC_ACCEPTED)
995                                         .entity(camundaJSONResponseBody).build();
996                 } else {
997                         List<String> variables = new ArrayList<>();
998                         variables.add(bpelStatus + "");
999                         String camundaJSONResponseBody = respHandler.getContent();
1000                         if (camundaJSONResponseBody != null
1001                                         && !camundaJSONResponseBody.isEmpty()) {
1002                                 Response resp = msoRequest.buildServiceErrorResponse(
1003                                                 bpelStatus, MsoException.ServiceException,
1004                                                 "Request Failed due to BPEL error with HTTP Status= %1 "
1005                                                                 + '\n' + camundaJSONResponseBody,
1006                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables);
1007                                 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
1008                                                 requestClient.getUrl(), "", "",
1009                                                 MsoLogger.ErrorCode.BusinessProcesssError,
1010                                                 "Response from BPEL engine is failed with HTTP Status="
1011                                                                 + bpelStatus);
1012                                 msoLogger.recordAuditEvent(startTime,
1013                                                 MsoLogger.StatusCode.ERROR,
1014                                                 MsoLogger.ResponseCode.InternalError,
1015                                                 "Response from BPMN engine is failed");
1016                                 msoLogger.debug(END_OF_THE_TRANSACTION
1017                                                 + (String) resp.getEntity());
1018                                 return resp;
1019                         } else {
1020                                 Response resp = msoRequest
1021                                                 .buildServiceErrorResponse(
1022                                                                 bpelStatus,
1023                                                                 MsoException.ServiceException,
1024                                                                 "Request Failed due to BPEL error with HTTP Status= %1",
1025                                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
1026                                                                 variables);
1027                                 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
1028                                                 requestClient.getUrl(), "", "",
1029                                                 MsoLogger.ErrorCode.BusinessProcesssError,
1030                                                 "Response from BPEL engine is empty");
1031                                 msoLogger.recordAuditEvent(startTime,
1032                                                 MsoLogger.StatusCode.ERROR,
1033                                                 MsoLogger.ResponseCode.InternalError,
1034                                                 "Response from BPEL engine is empty");
1035                                 msoLogger.debug(END_OF_THE_TRANSACTION
1036                                                 + (String) resp.getEntity());
1037                                 return resp;
1038                         }
1039                 }
1040         }
1041
1042         /**
1043          * Getting recipes from catalogDb
1044          * 
1045          * @param db the catalog db
1046          * @param serviceModelUUID the service model version uuid
1047          * @param action the action for the service
1048          * @return the service recipe result
1049          */
1050         private RecipeLookupResult getServiceInstanceOrchestrationURI(
1051                         CatalogDatabase db, String serviceModelUUID, Action action) {
1052
1053                 RecipeLookupResult recipeLookupResult = getServiceURI(db, serviceModelUUID, action);
1054
1055                 if (recipeLookupResult != null) {
1056                         msoLogger.debug("Orchestration URI is: "
1057                                         + recipeLookupResult.getOrchestrationURI()
1058                                         + ", recipe Timeout is: "
1059                                         + Integer.toString(recipeLookupResult.getRecipeTimeout()));
1060                 } else {
1061                         msoLogger.debug("No matching recipe record found");
1062                 }
1063                 return recipeLookupResult;
1064         }
1065
1066         /**
1067          * Getting recipes from catalogDb
1068          * If Service recipe is not set, use default recipe, if set , use special recipe.
1069          * @param db the catalog db
1070          * @param serviceModelUUID the service version uuid
1071          * @param action the action of the service.
1072          * @return the service recipe result.
1073          */
1074         private RecipeLookupResult getServiceURI(CatalogDatabase db, String serviceModelUUID, Action action) {
1075
1076                 String defaultServiceModelName = "UUI_DEFAULT";
1077
1078                 Service defaultServiceRecord = db
1079                                 .getServiceByModelName(defaultServiceModelName);
1080                 ServiceRecipe defaultRecipe = db.getServiceRecipeByModelUUID(
1081                         defaultServiceRecord.getModelUUID(), action.name());
1082                 //set recipe as default generic recipe
1083                 ServiceRecipe recipe = defaultRecipe;
1084                 //check the service special recipe 
1085                 if(null != serviceModelUUID && ! serviceModelUUID.isEmpty()){
1086                       ServiceRecipe serviceSpecialRecipe = db.getServiceRecipeByModelUUID(
1087                               serviceModelUUID, action.name());
1088                       if(null != serviceSpecialRecipe){
1089                           //set service special recipe.
1090                           recipe = serviceSpecialRecipe;
1091                       }
1092                 }       
1093                 
1094                 if (recipe == null) {
1095                         return null;
1096                 }
1097                 return new RecipeLookupResult(recipe.getOrchestrationUri(),
1098                                 recipe.getRecipeTimeout(), recipe.getServiceParamXSD());
1099
1100         }
1101
1102         /**
1103          * Converting E2EServiceInstanceRequest to ServiceInstanceRequest and
1104          * passing it to camunda engine.
1105          * 
1106          * @param e2eSir
1107          * @return
1108          */
1109         private String mapReqJsonToSvcInstReq(E2EServiceInstanceRequest e2eSir,
1110                         String requestJSON) {
1111
1112                 sir = new ServiceInstancesRequest();
1113
1114                 String returnString = null;
1115                 RequestDetails requestDetails = new RequestDetails();
1116                 ModelInfo modelInfo = new ModelInfo();
1117
1118                 // ModelInvariantId
1119                 modelInfo.setModelInvariantId(e2eSir.getService().getServiceInvariantUuid());
1120
1121                 // modelNameVersionId
1122                 modelInfo.setModelNameVersionId(e2eSir.getService().getServiceUuid());
1123
1124                 // String modelInfoValue =
1125                 // e2eSir.getService().getParameters().getNodeTemplateName();
1126                 // String[] arrayOfInfo = modelInfoValue.split(":");
1127                 // String modelName = arrayOfInfo[0];
1128                 // String modelVersion = arrayOfInfo[1];
1129
1130                 // TODO: To ensure, if we dont get the values from the UUI
1131                 String modelName = "voLTE";
1132                 String modelVersion = "1.0";
1133                 // modelName
1134                 modelInfo.setModelName(modelName);
1135
1136                 // modelVersion
1137                 modelInfo.setModelVersion(modelVersion);
1138
1139                 // modelType
1140                 modelInfo.setModelType(ModelType.service);
1141
1142                 // setting modelInfo to requestDetails
1143                 requestDetails.setModelInfo(modelInfo);
1144
1145                 SubscriberInfo subscriberInfo = new SubscriberInfo();
1146
1147                 // globalsubscriberId
1148                 subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getGlobalSubscriberId());
1149
1150                 // setting subscriberInfo to requestDetails
1151                 requestDetails.setSubscriberInfo(subscriberInfo);
1152
1153                 RequestInfo requestInfo = new RequestInfo();
1154
1155                 // instanceName
1156                 requestInfo.setInstanceName(e2eSir.getService().getName());
1157
1158                 // source
1159                 requestInfo.setSource("UUI");
1160
1161                 // suppressRollback
1162                 requestInfo.setSuppressRollback(true);
1163
1164                 // setting requestInfo to requestDetails
1165                 requestDetails.setRequestInfo(requestInfo);
1166
1167                 RequestParameters requestParameters = new RequestParameters();
1168
1169                 // subscriptionServiceType
1170                 requestParameters.setSubscriptionServiceType("MOG");
1171
1172                 // Userparams
1173                 //List<E2EUserParam> userParams;
1174                 // userParams =
1175                 // e2eSir.getService().getParameters().getRequestParameters().getUserParams();
1176                 List<Map<String, Object>> userParamList = new ArrayList<>();
1177                 Map<String, Object> userParamMap = new HashMap<>();
1178                 // complete json request updated in the camunda
1179                 userParamMap.put("UUIRequest", requestJSON);
1180                 userParamMap.put("ServiceInstanceName", e2eSir.getService().getName());
1181
1182                 // Map<String, String> userParamMap3 = null;
1183                 // for (E2EUserParam userp : userParams) {
1184                 // userParamMap.put(userp.getName(), userp.getValue());
1185                 //
1186                 // }
1187                 userParamList.add(userParamMap);
1188                 requestParameters.setUserParams(userParamList);
1189
1190                 // setting requestParameters to requestDetails
1191                 requestDetails.setRequestParameters(requestParameters);
1192
1193                 sir.setRequestDetails(requestDetails);
1194
1195                 // converting to string
1196                 ObjectMapper mapper = new ObjectMapper();
1197                 try {
1198                         returnString = mapper.writeValueAsString(sir);
1199                 } catch (IOException e) {
1200                         msoLogger
1201                                         .debug("Exception while converting ServiceInstancesRequest object to string",
1202                                                         e);
1203                 }
1204
1205                 return returnString;
1206         }
1207
1208 }