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