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