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