2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. 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
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  20 package org.openecomp.mso.apihandlerinfra;
 
  22 import java.util.ArrayList;
 
  23 import java.util.HashMap;
 
  24 import java.util.List;
 
  26 import javax.ws.rs.Consumes;
 
  27 import javax.ws.rs.DELETE;
 
  28 import javax.ws.rs.POST;
 
  29 import javax.ws.rs.PUT;
 
  30 import javax.ws.rs.Path;
 
  31 import javax.ws.rs.PathParam;
 
  32 import javax.ws.rs.Produces;
 
  33 import javax.ws.rs.core.MediaType;
 
  34 import javax.ws.rs.core.Response;
 
  36 import org.apache.http.HttpResponse;
 
  37 import org.apache.http.HttpStatus;
 
  38 import org.codehaus.jackson.map.ObjectMapper;
 
  40 import org.openecomp.mso.apihandler.common.*;
 
  41 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.*;
 
  42 import org.openecomp.mso.db.catalog.CatalogDatabase;
 
  43 import org.openecomp.mso.db.catalog.beans.*;
 
  44 import org.openecomp.mso.logger.MessageEnum;
 
  45 import org.openecomp.mso.logger.MsoAlarmLogger;
 
  46 import org.openecomp.mso.logger.MsoLogger;
 
  47 import org.openecomp.mso.properties.MsoJavaProperties;
 
  48 import org.openecomp.mso.properties.MsoPropertiesFactory;
 
  49 import org.openecomp.mso.requestsdb.InfraActiveRequests;
 
  50 import org.openecomp.mso.requestsdb.RequestsDatabase;
 
  51 import org.openecomp.mso.utils.UUIDChecker;
 
  53 @Path("/serviceInstances/{version:[vV][2-3]}")
 
  54 public class ServiceInstances {
 
  56     private HashMap<String, String> instanceIdMap = new HashMap<String,String>();
 
  58     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
 
  60     private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
 
  62     public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
 
  64     private static MsoJavaProperties props = MsoPropertiesUtils.loadMsoProperties ();
 
  69         public ServiceInstances() {
 
  70                 // TODO Auto-generated constructor stub
 
  75         @Consumes(MediaType.APPLICATION_JSON)
 
  76         @Produces(MediaType.APPLICATION_JSON)
 
  77         public Response createServiceInstance(String request, @PathParam("version") String version) {
 
  79                 Response response = serviceInstances(request, Action.createInstance, null, version);
 
  85         @Path("/{serviceInstanceId}")
 
  86         @Consumes(MediaType.APPLICATION_JSON)
 
  87         @Produces(MediaType.APPLICATION_JSON)
 
  88         public Response deleteServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
 
  90                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
  91                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
 
  96         @Path("/{serviceInstanceId}/vnfs")
 
  97         @Consumes(MediaType.APPLICATION_JSON)
 
  98         @Produces(MediaType.APPLICATION_JSON)
 
  99         public Response createVnfInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
 
 100         msoLogger.debug ("version is: " + version);
 
 101                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 102                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
 
 108         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}")
 
 109         @Consumes(MediaType.APPLICATION_JSON)
 
 110         @Produces(MediaType.APPLICATION_JSON)
 
 111         public Response deleteVnfInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
 
 112                                                                                                           @PathParam("vnfInstanceId") String vnfInstanceId) {
 
 114                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 115                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
 
 116                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
 
 122         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules")
 
 123         @Consumes(MediaType.APPLICATION_JSON)
 
 124         @Produces(MediaType.APPLICATION_JSON)
 
 125         public Response createVfModuleInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
 
 126                                                                                                                    @PathParam("vnfInstanceId") String vnfInstanceId) {
 
 127         msoLogger.debug ("version is: " + version);
 
 128                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 129                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
 
 130                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
 
 136         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
 
 137         @Consumes(MediaType.APPLICATION_JSON)
 
 138         @Produces(MediaType.APPLICATION_JSON)
 
 139         public Response updateVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
 
 140                                                                                                                    @PathParam("vnfInstanceId") String vnfInstanceId,
 
 141                                                                                                                    @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId) {
 
 143                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 144                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
 
 145                 instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
 
 146                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
 
 152         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
 
 153         @Consumes(MediaType.APPLICATION_JSON)
 
 154         @Produces(MediaType.APPLICATION_JSON)
 
 155         public Response deleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
 
 156                                                                                                                                                 @PathParam("vnfInstanceId") String vnfInstanceId,
 
 157                                                                                                                                                 @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId) {
 
 160                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 161                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
 
 162                 instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
 
 163                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
 
 170         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups")
 
 171         @Consumes(MediaType.APPLICATION_JSON)
 
 172         @Produces(MediaType.APPLICATION_JSON)
 
 173         public Response createVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
 
 174                                                                                        @PathParam("vnfInstanceId") String vnfInstanceId) {
 
 176                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 177                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
 
 178                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
 
 184         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
 
 185         @Consumes(MediaType.APPLICATION_JSON)
 
 186         @Produces(MediaType.APPLICATION_JSON)
 
 187         public Response updateVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
 
 188                                                                                                                                                    @PathParam("vnfInstanceId") String vnfInstanceId,
 
 189                                                                                                                                                    @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId) {
 
 192                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 193                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
 
 194                 instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
 
 195                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
 
 201         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
 
 202         @Consumes(MediaType.APPLICATION_JSON)
 
 203         @Produces(MediaType.APPLICATION_JSON)
 
 204         public Response deleteVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
 
 205                                                                                                                                                    @PathParam("vnfInstanceId") String vnfInstanceId,
 
 206                                                                                                                                                    @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId) {
 
 209                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 210                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
 
 211                 instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
 
 212                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
 
 218         @Path("/{serviceInstanceId}/networks")
 
 219         @Consumes(MediaType.APPLICATION_JSON)
 
 220         @Produces(MediaType.APPLICATION_JSON)
 
 221         public Response createNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
 
 223                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 224                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
 
 230         @Path("/{serviceInstanceId}/networks/{networkInstanceId}")
 
 231         @Consumes(MediaType.APPLICATION_JSON)
 
 232         @Produces(MediaType.APPLICATION_JSON)
 
 233         public Response updateNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
 
 234                                                                                                                                            @PathParam("networkInstanceId") String networkInstanceId) {
 
 236                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 237                 instanceIdMap.put("networkInstanceId", networkInstanceId);
 
 238                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
 
 244         @Path("/{serviceInstanceId}/networks/{networkInstanceId}")
 
 245         @Consumes(MediaType.APPLICATION_JSON)
 
 246         @Produces(MediaType.APPLICATION_JSON)
 
 247         public Response deleteNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
 
 248                                                                                                                                            @PathParam("networkInstanceId") String networkInstanceId) {
 
 250                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 251                 instanceIdMap.put("networkInstanceId", networkInstanceId);
 
 252                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
 
 259         private Response serviceInstances(String requestJSON, Action action, HashMap<String,String> instanceIdMap, String version) {
 
 261            String requestId = UUIDChecker.generateUUID(msoLogger);
 
 262            long startTime = System.currentTimeMillis ();
 
 263            msoLogger.debug ("requestId is: " + requestId);
 
 264            ServiceInstancesRequest sir = null;
 
 266            MsoRequest msoRequest = new MsoRequest (requestId);
 
 270         ObjectMapper mapper = new ObjectMapper();
 
 271         sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
 
 273        } catch(Exception e){
 
 274            msoLogger.debug ("Mapping of request to JSON object failed : ", e);
 
 275            Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
 
 276                    "Mapping of request to JSON object failed.  " + e.getMessage(),
 
 277                    ErrorNumbers.SVC_BAD_PARAMETER, null);
 
 278            if (msoRequest.getRequestId () != null) {
 
 279                msoLogger.debug ("Mapping of request to JSON object failed");
 
 280                msoRequest.createRequestRecord (Status.FAILED, action);
 
 282            msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e);
 
 283            msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Mapping of request to JSON object failed");
 
 284            msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 290                    msoRequest.parse(sir, instanceIdMap, action, version);
 
 291        } catch (Exception e) {
 
 292            msoLogger.debug ("Validation failed: ", e);
 
 293            Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
 
 294                    "Error parsing request.  " + e.getMessage(),
 
 295                    ErrorNumbers.SVC_BAD_PARAMETER, null);
 
 296            if (msoRequest.getRequestId () != null) {
 
 297                msoLogger.debug ("Logging failed message to the database");
 
 298                msoRequest.createRequestRecord (Status.FAILED, action);
 
 300            msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e);
 
 301            msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Validation of the input request failed");
 
 302            msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 306            InfraActiveRequests dup = null;
 
 307            String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
 
 308            String requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
 
 310            if(!(instanceName==null && requestScope.equals("service") && action == Action.createInstance)){
 
 311                dup = RequestsDatabase.checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope);
 
 313           } catch (Exception e) {
 
 314            msoLogger.error (MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e);
 
 316           Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, MsoException.ServiceException,
 
 318                                                                  ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
 
 322           msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Error during duplicate check");
 
 323           msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 328                  // Found the duplicate record. Return the appropriate error.
 
 329                    String instance = null;
 
 330                    if(instanceName != null){
 
 331                            instance = instanceName;
 
 333                            instance = instanceIdMap.get(requestScope + "InstanceId");
 
 335                    String dupMessage = "Error: Locked instance - This " + requestScope + " (" + instance + ") " + "already has a request being worked with a status of " + dup.getRequestStatus() + " (RequestId - " + dup.getRequestId() + "). The existing request must finish or be cleaned up before proceeding.";
 
 336            //List<String> variables = new ArrayList<String>();
 
 337            //variables.add(dup.getRequestStatus());
 
 339            Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, MsoException.ServiceException,
 
 341                    ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
 
 345            msoLogger.warn (MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError, "Duplicate request - Subscriber already has a request for this service");
 
 346            msoRequest.createRequestRecord (Status.FAILED, action);
 
 347            msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, dupMessage);
 
 348            msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 353            ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
 
 355            RequestReferences referencesResponse = new RequestReferences();
 
 357            referencesResponse.setRequestId(requestId);
 
 359            serviceResponse.setRequestReferences(referencesResponse);
 
 361         CatalogDatabase db = null;
 
 363             db = new CatalogDatabase ();
 
 364         } catch (Exception e) {
 
 365             msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
 
 366             msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
 
 367             Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
 
 368                     MsoException.ServiceException,
 
 369                     "No communication to catalog DB " + e.getMessage (),
 
 370                     ErrorNumbers.SVC_NO_SERVER_RESOURCES,
 
 372             alarmLogger.sendAlarm ("MsoDatabaseAccessError",
 
 373                     MsoAlarmLogger.CRITICAL,
 
 374                     Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
 
 375             msoRequest.createRequestRecord (Status.FAILED,action);
 
 376             msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with DB");
 
 377             msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 383            RecipeLookupResult recipeLookupResult = null;
 
 385                recipeLookupResult = getServiceInstanceOrchestrationURI (db, msoRequest, action);
 
 386            } catch (ValidationException e) {
 
 387                msoLogger.debug ("Validation failed: ", e);
 
 388                Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
 
 389                        "Error validating request.  " + e.getMessage(),
 
 390                        ErrorNumbers.SVC_BAD_PARAMETER, null);
 
 391                if (msoRequest.getRequestId () != null) {
 
 392                    msoLogger.debug ("Logging failed message to the database");
 
 393                    msoRequest.createRequestRecord (Status.FAILED, action);
 
 395                msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e);
 
 396                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Validation of the input request failed");
 
 397                msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 399            } catch (Exception e) {
 
 400                msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Exception while querying Catalog DB", e);
 
 401                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
 
 402                Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
 
 403                        MsoException.ServiceException,
 
 404                        "Recipe could not be retrieved from catalog DB " + e.getMessage (),
 
 405                        ErrorNumbers.SVC_GENERAL_SERVICE_ERROR,
 
 407                alarmLogger.sendAlarm ("MsoDatabaseAccessError",
 
 408                        MsoAlarmLogger.CRITICAL,
 
 409                        Messages.errors.get (ErrorNumbers.ERROR_FROM_CATALOG_DB));
 
 410                msoRequest.createRequestRecord (Status.FAILED,action);
 
 411                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while querying Catalog DB");
 
 412                msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 417            if (recipeLookupResult == null) {
 
 418                msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "No recipe found in DB");
 
 419                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
 
 420                Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
 
 421                        MsoException.ServiceException,
 
 422                        "Recipe does not exist in catalog DB",
 
 423                        ErrorNumbers.SVC_GENERAL_SERVICE_ERROR,
 
 425                msoRequest.createRequestRecord (Status.FAILED, action);
 
 426                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No recipe found in DB");
 
 427                msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 433            Boolean isBaseVfModule = false;
 
 435            if (msoRequest.getModelInfo().getModelType().equals(ModelType.vfModule)) {
 
 436                String asdcServiceModelVersion = msoRequest.getAsdcServiceModelVersion ();
 
 438                // Get VF Module-specific base module indicator
 
 441                if (asdcServiceModelVersion != null && !asdcServiceModelVersion.isEmpty ()) {
 
 442                    vfm = db.getVfModuleType (msoRequest.getVfModuleType (), asdcServiceModelVersion);
 
 445                    vfm = db.getVfModuleType (msoRequest.getVfModuleType ());
 
 449                    if (vfm.getIsBase() == 1) {
 
 450                        isBaseVfModule = true;
 
 453                else if (action == Action.createInstance || action == Action.updateInstance){
 
 454                    // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in Catalog DB.
 
 455                    // This request cannot proceed
 
 456                    msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "VF Module Type", "", MsoLogger.ErrorCode.DataError, "No VfModuleType found in DB");
 
 457                    msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
 
 458                    String serviceVersionText = "";
 
 459                    if (asdcServiceModelVersion != null && !asdcServiceModelVersion.isEmpty ()) {
 
 460                        serviceVersionText = " with version " + asdcServiceModelVersion;
 
 462                    Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
 
 463                            MsoException.ServiceException,
 
 464                            "VnfType " + msoRequest.getVnfType () + " and VF Module Model Name " + msoRequest.getVfModuleModelName() + serviceVersionText + " not found in MSO Catalog DB",
 
 465                            ErrorNumbers.SVC_BAD_PARAMETER,
 
 467                    msoRequest.createRequestRecord (Status.FAILED, action);
 
 468                    msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No matching vfModuleType found in DB");
 
 469                    msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 477            String serviceInstanceId = "";
 
 479            String vfModuleId = "";
 
 480            String volumeGroupId = "";
 
 481            String networkId = "";
 
 482            ServiceInstancesRequest siReq = msoRequest.getServiceInstancesRequest();
 
 484            if(siReq.getServiceInstanceId () != null){
 
 485                serviceInstanceId = siReq.getServiceInstanceId ();
 
 488            if(siReq.getVnfInstanceId () != null){
 
 489                vnfId = siReq.getVnfInstanceId ();
 
 492            if(siReq.getVfModuleInstanceId () != null){
 
 493                vfModuleId = siReq.getVfModuleInstanceId ();
 
 496            if(siReq.getVolumeGroupInstanceId () != null){
 
 497                volumeGroupId = siReq.getVolumeGroupInstanceId ();
 
 500            if(siReq.getNetworkInstanceId () != null){
 
 501                networkId = siReq.getNetworkInstanceId ();
 
 505            requestId = msoRequest.getRequestId ();
 
 506            msoLogger.debug ("requestId is: " + requestId);
 
 507            msoLogger.debug ("About to insert a record");
 
 510                msoRequest.createRequestRecord (Status.PENDING, action);
 
 511            } catch (Exception e) {
 
 512                msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC_REASON, "Exception while creating record in DB", "", "", MsoLogger.ErrorCode.SchemaError, "Exception while creating record in DB", e);
 
 513                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
 
 514                Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_INTERNAL_SERVER_ERROR,
 
 515                        MsoException.ServiceException,
 
 516                        "Exception while creating record in DB " + e.getMessage(),
 
 517                        ErrorNumbers.SVC_BAD_PARAMETER,
 
 519                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while creating record in DB");
 
 520                msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
 
 524            RequestClient requestClient = null;
 
 525            HttpResponse response = null;
 
 526            long subStartTime = System.currentTimeMillis();
 
 528                requestClient = RequestClientFactory.getRequestClient (recipeLookupResult.getOrchestrationURI (), props);
 
 529                // Capture audit event
 
 530                msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ());
 
 532                System.out.println("URL : " + requestClient.getUrl ());
 
 534                response = requestClient.post(requestId, isBaseVfModule, recipeLookupResult.getRecipeTimeout (), action.name (),
 
 535                        serviceInstanceId, vnfId, vfModuleId, volumeGroupId, networkId,
 
 536                        msoRequest.getServiceInstanceType (),
 
 537                        msoRequest.getVnfType (), msoRequest.getVfModuleType (),
 
 538                        msoRequest.getNetworkType (), msoRequest.getRequestJSON());
 
 540                msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI (), null);
 
 541            } catch (Exception e) {
 
 542                msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI (), null);
 
 543                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
 
 544                Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,
 
 545                        MsoException.ServiceException,
 
 546                        "Failed calling bpmn " + e.getMessage (),
 
 547                        ErrorNumbers.SVC_NO_SERVER_RESOURCES,
 
 549                alarmLogger.sendAlarm ("MsoConfigurationError",
 
 550                        MsoAlarmLogger.CRITICAL,
 
 551                        Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
 
 552                msoRequest.updateFinalStatus (Status.FAILED);
 
 553                msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
 
 554                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine");
 
 555                msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
 
 559            if (response == null) {
 
 560                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
 
 561                Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,
 
 562                        MsoException.ServiceException,
 
 563                        "bpelResponse is null",
 
 564                        ErrorNumbers.SVC_NO_SERVER_RESOURCES,
 
 566                msoRequest.updateFinalStatus (Status.FAILED);
 
 567                msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
 
 568                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Null response from BPMN");
 
 569                msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
 
 573            ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
 
 574            int bpelStatus = respHandler.getStatus ();
 
 576            // BPEL accepted the request, the request is in progress
 
 577            if (bpelStatus == HttpStatus.SC_ACCEPTED) {
 
 578                String camundaJSONResponseBody = respHandler.getResponseBody ();
 
 579                msoLogger.debug ("Received from Camunda: " + camundaJSONResponseBody);
 
 580                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.IN_PROGRESS);
 
 581                RequestsDatabase.updateInfraStatus (msoRequest.getRequestId (),
 
 582                        Status.IN_PROGRESS.toString (),
 
 583                        Constants.PROGRESS_REQUEST_IN_PROGRESS,
 
 584                        Constants.MODIFIED_BY_APIHANDLER);
 
 585                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN accepted the request, the request is in progress");
 
 586                msoLogger.debug ("End of the transaction, the final response is: " + (String) camundaJSONResponseBody);
 
 587                return Response.status (HttpStatus.SC_ACCEPTED).entity (camundaJSONResponseBody).build ();
 
 589                List<String> variables = new ArrayList<String>();
 
 590                variables.add(bpelStatus + "");
 
 591                String camundaJSONResponseBody = respHandler.getResponseBody ();
 
 592                if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty ()) {
 
 593                    msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
 
 594                    Response resp =  msoRequest.buildServiceErrorResponse(bpelStatus,
 
 595                            MsoException.ServiceException,
 
 596                            "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody,
 
 597                            ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
 
 599                    msoRequest.updateFinalStatus (Status.FAILED);
 
 600                    msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is failed with HTTP Status=" + bpelStatus);
 
 601                    msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPMN engine is failed");
 
 602                    msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
 
 605                    msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
 
 606                    Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,
 
 607                            MsoException.ServiceException,
 
 608                            "Request Failed due to BPEL error with HTTP Status= %1" ,
 
 609                            ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
 
 611                    msoRequest.updateFinalStatus (Status.FAILED);
 
 612                    msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty");
 
 613                    msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPEL engine is empty");
 
 614                    msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
 
 619            //return Response.status (HttpStatus.SC_ACCEPTED).entity (serviceResponse).build ();
 
 620            // return serviceResponse;
 
 623     private RecipeLookupResult getServiceInstanceOrchestrationURI (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
 
 624         RecipeLookupResult recipeLookupResult = null;
 
 625         //if the aLaCarte flag is set to TRUE, the API-H should choose the â€œVID_DEFAULTâ€
\9d recipe for the requested action
 
 627         msoLogger.debug("aLaCarteFlag is " + msoRequest.getALaCarteFlag());
 
 628         // Query MSO Catalog DB
 
 630         if (msoRequest.getModelInfo().getModelType().equals(ModelType.service)) {
 
 631             recipeLookupResult = getServiceURI(db, msoRequest, action);
 
 633         else if (msoRequest.getModelInfo().getModelType().equals(ModelType.vfModule) ||
 
 634                 msoRequest.getModelInfo().getModelType().equals(ModelType.volumeGroup) || msoRequest.getModelInfo().getModelType().equals(ModelType.vnf)) {
 
 636             recipeLookupResult = getVnfOrVfModuleUri(db, msoRequest, action);
 
 638         }else if (msoRequest.getModelInfo().getModelType().equals(ModelType.network)) {
 
 640             recipeLookupResult = getNetworkUri(db, msoRequest, action);
 
 643         if (recipeLookupResult != null) {
 
 644             msoLogger.debug ("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + Integer.toString(recipeLookupResult.getRecipeTimeout ()));
 
 647             msoLogger.debug("No matching recipe record found");
 
 649         return recipeLookupResult;
 
 653     private RecipeLookupResult getServiceURI (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
 
 655         // Construct the default service name
 
 656         // TODO need to make this a configurable property
 
 657         String defaultServiceName = msoRequest.getRequestInfo().getSource() + "_DEFAULT";
 
 659         Service serviceRecord = null;
 
 660         if(msoRequest.getALaCarteFlag()){
 
 661             serviceRecord = db.getServiceByName(defaultServiceName);
 
 663             serviceRecord = db.getServiceByVersionAndInvariantId(msoRequest.getModelInfo().getModelInvariantId(), msoRequest.getModelInfo().getModelVersion());
 
 666         ServiceRecipe recipe = null;
 
 667         if(serviceRecord !=null){
 
 668             serviceId = serviceRecord.getId();
 
 669             recipe = db.getServiceRecipe(serviceId, action.name());
 
 671         //if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
 
 672         RequestParameters reqParam = msoRequest.getServiceInstancesRequest().getRequestDetails().getRequestParameters();
 
 673         if(reqParam!=null && reqParam.isALaCarteSet() && recipe==null){
 
 675         }else if (recipe == null) {  //aLaCarte wasn't sent, so we'll try the default
 
 676             serviceRecord = db.getServiceByName(defaultServiceName);
 
 677             serviceId = serviceRecord.getId();
 
 678             recipe = db.getServiceRecipe(serviceId, action.name());
 
 683         return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
 
 687     private RecipeLookupResult getVnfOrVfModuleUri (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
 
 689         String vnfComponentType = msoRequest.getModelInfo().getModelType().name();
 
 691         RelatedInstanceList[] instanceList = null;
 
 692         if (msoRequest.getServiceInstancesRequest().getRequestDetails() != null) {
 
 693             instanceList = msoRequest.getServiceInstancesRequest().getRequestDetails().getRelatedInstanceList();
 
 696         String serviceModelName = null;
 
 697         String vnfModelName = null;
 
 698         String asdcServiceModelVersion = null;
 
 699         String modelVersion = msoRequest.getModelInfo().getModelVersion();
 
 700         Recipe recipe = null;
 
 701         String defaultVnfType = msoRequest.getRequestInfo().getSource() + "_DEFAULT";
 
 702         String modelCustomizationId = msoRequest.getModelInfo().getModelCustomizationId();
 
 703         String vfModuleModelName = msoRequest.getModelInfo().getModelName();
 
 704         if (instanceList != null) {
 
 706             for(RelatedInstanceList relatedInstanceList : instanceList){
 
 708                 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
 
 709                 ModelInfo modelInfo = relatedInstance.getModelInfo();
 
 710                 if(modelInfo.getModelType().equals(ModelType.service)){
 
 711                     serviceModelName = modelInfo.getModelName();
 
 712                     asdcServiceModelVersion = modelInfo.getModelVersion();
 
 715                 if(modelInfo.getModelType().equals(ModelType.vnf)){
 
 716                     vnfModelName = modelInfo.getModelCustomizationName();
 
 717                     if (null == vnfModelName || vnfModelName.trim().isEmpty()) {
 
 718                         VnfResource vnfResource = db.getVnfResourceByModelCustomizationId(modelInfo.getModelCustomizationUuid(), modelInfo.getModelVersion());
 
 719                         vnfModelName = vnfResource.getModelName();
 
 724             if(msoRequest.getModelInfo().getModelType().equals(ModelType.vnf)) {
 
 725                 String modelCustomizationName = msoRequest.getModelInfo().getModelCustomizationName();
 
 727                 VnfResource vnfResource = null;
 
 729                 // Validation for vnfResource
 
 730                 if(modelCustomizationName!=null) {
 
 731                     vnfResource = db.getVnfResource(serviceModelName + "/" + modelCustomizationName, asdcServiceModelVersion);
 
 733                     vnfResource = db.getVnfResourceByModelCustomizationId(modelCustomizationId, asdcServiceModelVersion);
 
 736                 if(vnfResource==null){
 
 737                     throw new ValidationException("catalog entry");
 
 740                 VnfRecipe vnfRecipe = db.getVnfRecipe(defaultVnfType, action.name());
 
 742                 if (vnfRecipe == null) {
 
 746                 return new RecipeLookupResult (vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
 
 748                 String vnfType = serviceModelName + "/" + vnfModelName;
 
 749                 String vfModuleType = vnfType + "::" + vfModuleModelName;
 
 750                 List<VfModule> vfModule = db.getVfModule(vfModuleType, modelCustomizationId, asdcServiceModelVersion, modelVersion, action.name());
 
 751                 if(vfModule==null || vfModule.isEmpty()){
 
 752                     throw new ValidationException("catalog entry");
 
 754                     if(!msoRequest.getALaCarteFlag() && action != Action.deleteInstance){
 
 755                         recipe = db.getVnfComponentsRecipeByVfModule(vfModule, action.name());
 
 758                 if (recipe == null) {
 
 759                     msoLogger.debug("recipe is null, getting default");
 
 760                     recipe = db.getVnfComponentsRecipeByVfModuleId("VID_DEFAULT", vnfComponentType, action.name());
 
 762                     if (recipe == null) {
 
 769             msoLogger.debug("recipe is null, getting default");
 
 771             if(msoRequest.getModelInfo().getModelType().equals(ModelType.vnf)) {
 
 772                 recipe = db.getVnfRecipe(defaultVnfType, action.name());
 
 773                 if (recipe == null) {
 
 777                 recipe = db.getVnfComponentsRecipeByVfModuleId("VID_DEFAULT", vnfComponentType, action.name());
 
 779                 if (recipe == null) {
 
 785         return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
 
 788     private RecipeLookupResult getNetworkUri (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
 
 790         String defaultNetworkType = msoRequest.getRequestInfo().getSource() + "_DEFAULT";
 
 792         String modelName = msoRequest.getModelInfo().getModelName();
 
 793         Recipe recipe = null;
 
 794         if(msoRequest.getALaCarteFlag()){
 
 795             recipe = db.getNetworkRecipe(defaultNetworkType, action.name());
 
 797             if(msoRequest.getModelInfo().getModelCustomizationId()!=null){
 
 798                 NetworkResource networkResource = db.getNetworkResourceByModelCustUuid(msoRequest.getModelInfo().getModelCustomizationId());
 
 799                 if(networkResource!=null){
 
 800                     recipe = db.getNetworkRecipe(networkResource.getNetworkType(), action.name());
 
 802                     throw new ValidationException("no catalog entry found");
 
 806                 recipe = db.getNetworkRecipe(modelName, action.name());
 
 809                 recipe = db.getNetworkRecipe(defaultNetworkType, action.name());
 
 812         if (recipe == null) {
 
 815         return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());