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