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