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