Change the header to SO
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / ServiceInstances.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
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 package org.openecomp.mso.apihandlerinfra;
21
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25
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;
35
36 import org.apache.http.HttpResponse;
37 import org.apache.http.HttpStatus;
38 import org.codehaus.jackson.map.ObjectMapper;
39 import org.openecomp.mso.apihandler.common.ErrorNumbers;
40 import org.openecomp.mso.apihandler.common.RequestClient;
41 import org.openecomp.mso.apihandler.common.RequestClientFactory;
42 import org.openecomp.mso.apihandler.common.ResponseHandler;
43 import org.openecomp.mso.apihandler.common.ValidationException;
44 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ModelInfo;
45 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RelatedInstance;
46 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RelatedInstanceList;
47 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestParameters;
48 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestReferences;
49 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ServiceInstancesRequest;
50 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ServiceInstancesResponse;
51 import org.openecomp.mso.db.catalog.CatalogDatabase;
52 import org.openecomp.mso.db.catalog.beans.NetworkResource;
53 import org.openecomp.mso.db.catalog.beans.Recipe;
54 import org.openecomp.mso.db.catalog.beans.Service;
55 import org.openecomp.mso.db.catalog.beans.ServiceRecipe;
56 import org.openecomp.mso.db.catalog.beans.VfModule;
57 import org.openecomp.mso.db.catalog.beans.VfModuleCustomization;
58 import org.openecomp.mso.db.catalog.beans.VnfRecipe;
59 import org.openecomp.mso.db.catalog.beans.VnfResource;
60 import org.openecomp.mso.db.catalog.beans.VnfResourceCustomization;
61 import org.openecomp.mso.logger.MessageEnum;
62 import org.openecomp.mso.logger.MsoAlarmLogger;
63 import org.openecomp.mso.logger.MsoLogger;
64 import org.openecomp.mso.requestsdb.InfraActiveRequests;
65 import org.openecomp.mso.requestsdb.RequestsDatabase;
66 import org.openecomp.mso.utils.UUIDChecker;
67
68 import com.wordnik.swagger.annotations.Api;
69 import com.wordnik.swagger.annotations.ApiOperation;
70
71 @Path("/serviceInstances")
72 @Api(value="/serviceInstances",description="API Requests for Service Instances")
73 public class ServiceInstances {
74
75         private HashMap<String, String> instanceIdMap = new HashMap<String,String>();
76         private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
77         private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
78         public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
79
80         @POST
81         @Path("/{version:[vV][3-5]}")
82         @Consumes(MediaType.APPLICATION_JSON)
83         @Produces(MediaType.APPLICATION_JSON)
84         @ApiOperation(value="Create a Service Instance on a version provided",response=Response.class)
85         public Response createServiceInstance(String request, @PathParam("version") String version) {
86
87                 Response response = serviceInstances(request, Action.createInstance, null, version);
88
89                 return response;
90         }
91         
92         @POST
93         @Path("/{version:[vV][5]}/{serviceInstanceId}/activate")
94         @Consumes(MediaType.APPLICATION_JSON)
95         @Produces(MediaType.APPLICATION_JSON)
96         @ApiOperation(value="Activate provided Service Instance",response=Response.class)
97         public Response activateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
98
99                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
100                 Response response = serviceInstances(request, Action.activateInstance, instanceIdMap, version);
101
102                 return response;
103         }
104         
105         @POST
106         @Path("/{version:[vV][5]}/{serviceInstanceId}/deactivate")
107         @Consumes(MediaType.APPLICATION_JSON)
108         @Produces(MediaType.APPLICATION_JSON)
109         @ApiOperation(value="Deactivate provided Service Instance",response=Response.class)
110         public Response deactivateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
111
112                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
113                 Response response = serviceInstances(request, Action.deactivateInstance, instanceIdMap, version);
114
115                 return response;
116         }
117         
118
119         @DELETE
120         @Path("/{version:[vV][3-5]}/{serviceInstanceId}")
121         @Consumes(MediaType.APPLICATION_JSON)
122         @Produces(MediaType.APPLICATION_JSON)
123         @ApiOperation(value="Delete provided Service Instance",response=Response.class)
124         public Response deleteServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
125
126                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
127                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
128                 return response;
129         }
130
131         @POST
132         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/vnfs")
133         @Consumes(MediaType.APPLICATION_JSON)
134         @Produces(MediaType.APPLICATION_JSON)
135         @ApiOperation(value="Create VNF on a specified version and serviceInstance",response=Response.class)
136         public Response createVnfInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
137                 msoLogger.debug ("version is: " + version);
138                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
139                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
140
141                 return response;
142         }
143         
144         @POST
145         @Path("/{version:[vV][5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}/replace")
146         @Consumes(MediaType.APPLICATION_JSON)
147         @Produces(MediaType.APPLICATION_JSON)
148         @ApiOperation(value="Replace provided VNF instance",response=Response.class)
149         public Response replaceVnfInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
150                         @PathParam("vnfInstanceId") String vnfInstanceId) {
151                 msoLogger.debug ("version is: " + version);
152                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
153                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
154                 Response response = serviceInstances(request, Action.replaceInstance, instanceIdMap, version);
155
156                 return response;
157         }
158         
159         @PUT
160         @Path("/{version:[vV][5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}")
161         @Consumes(MediaType.APPLICATION_JSON)
162         @Produces(MediaType.APPLICATION_JSON)
163         @ApiOperation(value="Update VNF on a specified version, serviceInstance and vnfInstance",response=Response.class)
164         public Response updateVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
165                         @PathParam("vnfInstanceId") String vnfInstanceId) {                     
166
167                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
168                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);              
169                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
170
171                 return response;
172         }
173
174
175         @DELETE
176         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}")
177         @Consumes(MediaType.APPLICATION_JSON)
178         @Produces(MediaType.APPLICATION_JSON)
179         @ApiOperation(value="Delete provided VNF instance",response=Response.class)
180         public Response deleteVnfInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
181                         @PathParam("vnfInstanceId") String vnfInstanceId) {
182
183                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
184                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
185                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
186
187                 return response;
188         }
189
190         @POST
191         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules")
192         @Consumes(MediaType.APPLICATION_JSON)
193         @Produces(MediaType.APPLICATION_JSON)
194         @ApiOperation(value="Create VfModule on a specified version, serviceInstance and vnfInstance",response=Response.class)
195         public Response createVfModuleInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
196                         @PathParam("vnfInstanceId") String vnfInstanceId) {
197                 msoLogger.debug ("version is: " + version);
198                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
199                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
200                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
201
202                 return response;
203         }
204         
205         @POST
206         @Path("/{version:[vV][5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}/replace")
207         @Consumes(MediaType.APPLICATION_JSON)
208         @Produces(MediaType.APPLICATION_JSON)
209         @ApiOperation(value="Create VfModule on a specified version, serviceInstance and vnfInstance",response=Response.class)
210         public Response replaceVfModuleInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
211                         @PathParam("vnfInstanceId") String vnfInstanceId,
212                         @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId) {
213                 
214                 msoLogger.debug ("version is: " + version);
215                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
216                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
217                 instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
218                 Response response = serviceInstances(request, Action.replaceInstance, instanceIdMap, version);
219
220                 return response;
221         }
222
223         @PUT
224         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
225         @Consumes(MediaType.APPLICATION_JSON)
226         @Produces(MediaType.APPLICATION_JSON)
227         @ApiOperation(value="Update VfModule on a specified version, serviceInstance, vnfInstance and vfModule",response=Response.class)
228         public Response updateVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
229                         @PathParam("vnfInstanceId") String vnfInstanceId,
230                         @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId) {
231
232                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
233                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
234                 instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
235                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
236
237                 return response;
238         }
239
240         @DELETE
241         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
242         @Consumes(MediaType.APPLICATION_JSON)
243         @Produces(MediaType.APPLICATION_JSON)
244         @ApiOperation(value="Delete provided VfModule instance",response=Response.class)
245         public Response deleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
246                         @PathParam("vnfInstanceId") String vnfInstanceId,
247                         @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId) {
248
249
250                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
251                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
252                 instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
253                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
254
255                 return response;
256         }
257
258
259         @POST
260         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups")
261         @Consumes(MediaType.APPLICATION_JSON)
262         @Produces(MediaType.APPLICATION_JSON)
263         @ApiOperation(value="Create VolumeGroup on a specified version, serviceInstance, vnfInstance",response=Response.class)
264         public Response createVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
265                         @PathParam("vnfInstanceId") String vnfInstanceId) {
266
267                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
268                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
269                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
270
271                 return response;
272         }
273
274         @PUT
275         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
276         @Consumes(MediaType.APPLICATION_JSON)
277         @Produces(MediaType.APPLICATION_JSON)
278         @ApiOperation(value="Update VolumeGroup on a specified version, serviceInstance, vnfInstance and volumeGroup",response=Response.class)
279         public Response updateVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
280                         @PathParam("vnfInstanceId") String vnfInstanceId,
281                         @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId) {
282
283
284                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
285                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
286                 instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
287                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
288
289                 return response;
290         }
291
292         @DELETE
293         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
294         @Consumes(MediaType.APPLICATION_JSON)
295         @Produces(MediaType.APPLICATION_JSON)
296         @ApiOperation(value="Delete provided VolumeGroup instance",response=Response.class)
297         public Response deleteVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
298                         @PathParam("vnfInstanceId") String vnfInstanceId,
299                         @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId) {
300
301
302                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
303                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
304                 instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
305                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
306
307                 return response;
308         }
309
310         @POST
311         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/networks")
312         @Consumes(MediaType.APPLICATION_JSON)
313         @Produces(MediaType.APPLICATION_JSON)
314         @ApiOperation(value="Create NetworkInstance on a specified version and serviceInstance ",response=Response.class)
315         public Response createNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
316
317                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
318                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
319
320                 return response;
321         }
322
323         @PUT
324         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/networks/{networkInstanceId}")
325         @Consumes(MediaType.APPLICATION_JSON)
326         @Produces(MediaType.APPLICATION_JSON)
327         @ApiOperation(value="Update VolumeGroup on a specified version, serviceInstance, networkInstance",response=Response.class)
328         public Response updateNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
329                         @PathParam("networkInstanceId") String networkInstanceId) {
330
331                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
332                 instanceIdMap.put("networkInstanceId", networkInstanceId);
333                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
334
335                 return response;
336         }
337
338         @DELETE
339         @Path("/{version:[vV][3-5]}/{serviceInstanceId}/networks/{networkInstanceId}")
340         @Consumes(MediaType.APPLICATION_JSON)
341         @Produces(MediaType.APPLICATION_JSON)
342         @ApiOperation(value="Delete provided Network instance",response=Response.class)
343         public Response deleteNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
344                         @PathParam("networkInstanceId") String networkInstanceId) {
345
346                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
347                 instanceIdMap.put("networkInstanceId", networkInstanceId);
348                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
349
350                 return response;
351         }
352
353
354
355         private Response serviceInstances(String requestJSON, Action action, HashMap<String,String> instanceIdMap, String version) {
356
357                 String requestId = UUIDChecker.generateUUID(msoLogger);
358                 long startTime = System.currentTimeMillis ();
359                 msoLogger.debug ("requestId is: " + requestId);
360                 ServiceInstancesRequest sir = null;
361
362                 MsoRequest msoRequest = new MsoRequest (requestId);
363
364
365                 try{
366                         ObjectMapper mapper = new ObjectMapper();
367                         sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
368
369                 } catch(Exception e){
370                         msoLogger.debug ("Mapping of request to JSON object failed : ", e);
371                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
372                                         "Mapping of request to JSON object failed.  " + e.getMessage(),
373                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
374                         if (msoRequest.getRequestId () != null) {
375                                 msoLogger.debug ("Mapping of request to JSON object failed");
376                                 msoRequest.createRequestRecord (Status.FAILED, action);
377                         }
378                         msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e);
379                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Mapping of request to JSON object failed");
380                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
381                         return response;
382                 }
383
384
385                 try{
386                         msoRequest.parse(sir, instanceIdMap, action, version);
387                 } catch (Exception e) {
388                         msoLogger.debug ("Validation failed: ", e);
389                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
390                                         "Error parsing request.  " + e.getMessage(),
391                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
392                         if (msoRequest.getRequestId () != null) {
393                                 msoLogger.debug ("Logging failed message to the database");
394                                 msoRequest.createRequestRecord (Status.FAILED, action);
395                         }
396                         msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e);
397                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Validation of the input request failed");
398                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
399                         return response;
400                 }
401
402                 InfraActiveRequests dup = null;
403                 String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
404                 String requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
405                 try {
406                         if(!(instanceName==null && requestScope.equals("service") && (action == Action.createInstance || action == Action.activateInstance))){
407                                 dup = (RequestsDatabase.getInstance()).checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope);
408                         }
409                 } catch (Exception e) {
410                         msoLogger.error (MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e);
411
412                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, MsoException.ServiceException,
413                                         e.getMessage(),
414                                         ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
415                                         null) ;
416
417
418                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Error during duplicate check");
419                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
420                         return response;
421                 }
422
423                 if (dup != null) {
424                         // Found the duplicate record. Return the appropriate error.
425                         String instance = null;
426                         if(instanceName != null){
427                                 instance = instanceName;
428                         }else{
429                                 instance = instanceIdMap.get(requestScope + "InstanceId");
430                         }
431                         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.";
432                         //List<String> variables = new ArrayList<String>();
433                         //variables.add(dup.getRequestStatus());
434
435                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, MsoException.ServiceException,
436                                         dupMessage,
437                                         ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
438                                         null) ;
439
440
441                         msoLogger.warn (MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError, "Duplicate request - Subscriber already has a request for this service");
442                         msoRequest.createRequestRecord (Status.FAILED, action);
443                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, dupMessage);
444                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
445                         return response;
446                 }
447
448
449                 ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
450
451                 RequestReferences referencesResponse = new RequestReferences();
452
453                 referencesResponse.setRequestId(requestId);
454
455                 serviceResponse.setRequestReferences(referencesResponse);
456
457                 CatalogDatabase db = null;
458                 try {
459                         db = CatalogDatabase.getInstance();
460                 } catch (Exception e) {
461                         msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
462                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
463                         Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
464                                         MsoException.ServiceException,
465                                         "No communication to catalog DB " + e.getMessage (),
466                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,
467                                         null);
468                         alarmLogger.sendAlarm ("MsoDatabaseAccessError",
469                                         MsoAlarmLogger.CRITICAL,
470                                         Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
471                         msoRequest.createRequestRecord (Status.FAILED,action);
472                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with DB");
473                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
474                         return response;
475                 }
476
477
478
479                 RecipeLookupResult recipeLookupResult = null;
480                 try {
481                         recipeLookupResult = getServiceInstanceOrchestrationURI (db, msoRequest, action);
482                 } catch (ValidationException e) {
483                         msoLogger.debug ("Validation failed: ", e);
484                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
485                                         "Error validating request.  " + e.getMessage(),
486                                         ErrorNumbers.SVC_BAD_PARAMETER, null);
487                         if (msoRequest.getRequestId () != null) {
488                                 msoLogger.debug ("Logging failed message to the database");
489                                 msoRequest.createRequestRecord (Status.FAILED, action);
490                         }
491                         msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e);
492                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Validation of the input request failed");
493                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
494                         return response;
495                 } catch (Exception e) {
496                         msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Exception while querying Catalog DB", e);
497                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
498                         Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
499                                         MsoException.ServiceException,
500                                         "Recipe could not be retrieved from catalog DB " + e.getMessage (),
501                                         ErrorNumbers.SVC_GENERAL_SERVICE_ERROR,
502                                         null);
503                         alarmLogger.sendAlarm ("MsoDatabaseAccessError",
504                                         MsoAlarmLogger.CRITICAL,
505                                         Messages.errors.get (ErrorNumbers.ERROR_FROM_CATALOG_DB));
506                         msoRequest.createRequestRecord (Status.FAILED,action);
507                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while querying Catalog DB");
508                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
509                         db.close();
510                         return response;
511                 }
512
513                 if (recipeLookupResult == null) {
514                         msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "No recipe found in DB");
515                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
516                         Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
517                                         MsoException.ServiceException,
518                                         "Recipe does not exist in catalog DB",
519                                         ErrorNumbers.SVC_GENERAL_SERVICE_ERROR,
520                                         null);
521                         msoRequest.createRequestRecord (Status.FAILED, action);
522                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No recipe found in DB");
523                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
524                         db.close();
525                         return response;
526                 }
527
528
529                 Boolean isBaseVfModule = false;
530
531                 if (msoRequest.getModelInfo().getModelType().equals(ModelType.vfModule)) {
532                         String asdcServiceModelVersion = msoRequest.getAsdcServiceModelVersion ();
533
534                         // Get VF Module-specific base module indicator
535                         VfModule vfm = null;
536
537                         String modelVersionId = msoRequest.getModelInfo().getModelVersionId();
538
539                         if(modelVersionId != null) {
540                                 vfm = db.getVfModuleByModelUuid(modelVersionId);
541                         } else {
542                                 vfm = db.getVfModuleByModelInvariantUuidAndModelVersion(msoRequest.getModelInfo().getModelInvariantId(), msoRequest.getModelInfo().getModelVersion());
543                         }
544
545                         if (vfm != null) {
546                                 if (vfm.getIsBase() == 1) {
547                                         isBaseVfModule = true;
548                                 }
549                         }
550                         else if (action == Action.createInstance || action == Action.updateInstance){
551                                 // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in Catalog DB.
552                                 // This request cannot proceed
553                                 msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "VF Module Type", "", MsoLogger.ErrorCode.DataError, "No VfModuleType found in DB");
554                                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
555                                 String serviceVersionText = "";
556                                 if (asdcServiceModelVersion != null && !asdcServiceModelVersion.isEmpty ()) {
557                                         serviceVersionText = " with version " + asdcServiceModelVersion;
558                                 }
559                                 Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
560                                                 MsoException.ServiceException,
561                                                 "VnfType " + msoRequest.getVnfType () + " and VF Module Model Name " + msoRequest.getVfModuleModelName() + serviceVersionText + " not found in MSO Catalog DB",
562                                                 ErrorNumbers.SVC_BAD_PARAMETER,
563                                                 null);
564                                 msoRequest.createRequestRecord (Status.FAILED, action);
565                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No matching vfModuleType found in DB");
566                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
567                                 db.close();
568                                 return response;
569                         }
570                 }
571
572                 db.close();
573
574                 String serviceInstanceId = "";
575                 String vnfId = "";
576                 String vfModuleId = "";
577                 String volumeGroupId = "";
578                 String networkId = "";
579                 ServiceInstancesRequest siReq = msoRequest.getServiceInstancesRequest();
580
581                 if(siReq.getServiceInstanceId () != null){
582                         serviceInstanceId = siReq.getServiceInstanceId ();
583                 }
584
585                 if(siReq.getVnfInstanceId () != null){
586                         vnfId = siReq.getVnfInstanceId ();
587                 }
588
589                 if(siReq.getVfModuleInstanceId () != null){
590                         vfModuleId = siReq.getVfModuleInstanceId ();
591                 }
592
593                 if(siReq.getVolumeGroupInstanceId () != null){
594                         volumeGroupId = siReq.getVolumeGroupInstanceId ();
595                 }
596
597                 if(siReq.getNetworkInstanceId () != null){
598                         networkId = siReq.getNetworkInstanceId ();
599                 }
600
601
602                 requestId = msoRequest.getRequestId ();
603                 msoLogger.debug ("requestId is: " + requestId);
604                 msoLogger.debug ("About to insert a record");
605
606                 try {
607                         msoRequest.createRequestRecord (Status.PENDING, action);
608                 } catch (Exception e) {
609                         msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC_REASON, "Exception while creating record in DB", "", "", MsoLogger.ErrorCode.SchemaError, "Exception while creating record in DB", e);
610                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
611                         Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_INTERNAL_SERVER_ERROR,
612                                         MsoException.ServiceException,
613                                         "Exception while creating record in DB " + e.getMessage(),
614                                         ErrorNumbers.SVC_BAD_PARAMETER,
615                                         null);
616                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while creating record in DB");
617                         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
618                         return response;
619                 }
620
621                 RequestClient requestClient = null;
622                 HttpResponse response = null;
623                 long subStartTime = System.currentTimeMillis();
624                 try {
625                         requestClient = RequestClientFactory.getRequestClient (recipeLookupResult.getOrchestrationURI (), MsoPropertiesUtils.loadMsoProperties ());
626                         // Capture audit event
627                         msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ());
628
629                         System.out.println("URL : " + requestClient.getUrl ());
630
631                         response = requestClient.post(requestId, isBaseVfModule, recipeLookupResult.getRecipeTimeout (), action.name (),
632                                         serviceInstanceId, vnfId, vfModuleId, volumeGroupId, networkId,
633                                         msoRequest.getServiceInstanceType (),
634                                         msoRequest.getVnfType (), msoRequest.getVfModuleType (),
635                                         msoRequest.getNetworkType (), msoRequest.getRequestJSON());
636
637                         msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI (), null);
638                 } catch (Exception e) {
639                         msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI (), null);
640                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
641                         Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,
642                                         MsoException.ServiceException,
643                                         "Failed calling bpmn " + e.getMessage (),
644                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,
645                                         null);
646                         alarmLogger.sendAlarm ("MsoConfigurationError",
647                                         MsoAlarmLogger.CRITICAL,
648                                         Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
649                         msoRequest.updateFinalStatus (Status.FAILED);
650                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
651                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine");
652                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
653                         return resp;
654                 }
655
656                 if (response == null) {
657                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
658                         Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,
659                                         MsoException.ServiceException,
660                                         "bpelResponse is null",
661                                         ErrorNumbers.SVC_NO_SERVER_RESOURCES,
662                                         null);
663                         msoRequest.updateFinalStatus (Status.FAILED);
664                         msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
665                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Null response from BPMN");
666                         msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
667                         return resp;
668                 }
669
670                 ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
671                 int bpelStatus = respHandler.getStatus ();
672
673                 // BPEL accepted the request, the request is in progress
674                 if (bpelStatus == HttpStatus.SC_ACCEPTED) {
675                         String camundaJSONResponseBody = respHandler.getResponseBody ();
676                         msoLogger.debug ("Received from Camunda: " + camundaJSONResponseBody);
677                         msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.IN_PROGRESS);
678                         (RequestsDatabase.getInstance()).updateInfraStatus (msoRequest.getRequestId (),
679                                         Status.IN_PROGRESS.toString (),
680                                         Constants.PROGRESS_REQUEST_IN_PROGRESS,
681                                         Constants.MODIFIED_BY_APIHANDLER);
682                         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN accepted the request, the request is in progress");
683                         msoLogger.debug ("End of the transaction, the final response is: " + (String) camundaJSONResponseBody);
684                         return Response.status (HttpStatus.SC_ACCEPTED).entity (camundaJSONResponseBody).build ();
685                 } else {
686                         List<String> variables = new ArrayList<String>();
687                         variables.add(bpelStatus + "");
688                         String camundaJSONResponseBody = respHandler.getResponseBody ();
689                         if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty ()) {
690                                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
691                                 Response resp =  msoRequest.buildServiceErrorResponse(bpelStatus,
692                                                 MsoException.ServiceException,
693                                                 "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody,
694                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
695                                                 variables);
696                                 msoRequest.updateFinalStatus (Status.FAILED);
697                                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is failed with HTTP Status=" + bpelStatus);
698                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPMN engine is failed");
699                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
700                                 return resp;
701                         } else {
702                                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
703                                 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,
704                                                 MsoException.ServiceException,
705                                                 "Request Failed due to BPEL error with HTTP Status= %1" ,
706                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
707                                                 variables);
708                                 msoRequest.updateFinalStatus (Status.FAILED);
709                                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty");
710                                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPEL engine is empty");
711                                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
712                                 return resp;
713                         }
714                 }
715
716                 //return Response.status (HttpStatus.SC_ACCEPTED).entity (serviceResponse).build ();
717                 // return serviceResponse;
718         }
719
720         private RecipeLookupResult getServiceInstanceOrchestrationURI (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
721                 RecipeLookupResult recipeLookupResult = null;
722                 //if the aLaCarte flag is set to TRUE, the API-H should choose the â€œVID_DEFAULTâ€\9d recipe for the requested action
723
724                 msoLogger.debug("aLaCarteFlag is " + msoRequest.getALaCarteFlag());
725                 // Query MSO Catalog DB
726
727                 if (msoRequest.getModelInfo().getModelType().equals(ModelType.service)) {
728                         recipeLookupResult = getServiceURI(db, msoRequest, action);
729                 }
730                 else if (msoRequest.getModelInfo().getModelType().equals(ModelType.vfModule) ||
731                                 msoRequest.getModelInfo().getModelType().equals(ModelType.volumeGroup) || msoRequest.getModelInfo().getModelType().equals(ModelType.vnf)) {
732
733                         recipeLookupResult = getVnfOrVfModuleUri(db, msoRequest, action);
734
735                 }else if (msoRequest.getModelInfo().getModelType().equals(ModelType.network)) {
736
737                         recipeLookupResult = getNetworkUri(db, msoRequest, action);
738                 }
739
740                 if (recipeLookupResult != null) {
741                         msoLogger.debug ("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + Integer.toString(recipeLookupResult.getRecipeTimeout ()));
742                 }
743                 else {
744                         msoLogger.debug("No matching recipe record found");
745                 }
746                 return recipeLookupResult;
747         }
748
749
750         private RecipeLookupResult getServiceURI (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
751                 // SERVICE REQUEST
752                 // Construct the default service name
753                 // TODO need to make this a configurable property
754                 String defaultServiceModelName = msoRequest.getRequestInfo().getSource() + "_DEFAULT";
755
756                 Service serviceRecord = null;
757                 ModelInfo modelInfo = msoRequest.getModelInfo();
758                 if(msoRequest.getALaCarteFlag()){
759                         serviceRecord = db.getServiceByModelName(defaultServiceModelName);
760                 }else{
761                         serviceRecord = db.getServiceByModelUUID(modelInfo.getModelVersionId()); // ModelVersionId is not required in v3
762                         if(serviceRecord == null) {
763                                 serviceRecord = db.getServiceByVersionAndInvariantId(modelInfo.getModelInvariantId(), modelInfo.getModelVersion());
764                         }
765                 }
766
767                 ServiceRecipe recipe = null;
768                 if(serviceRecord !=null){
769                         recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name());
770                 }
771                 //if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
772                 RequestParameters reqParam = msoRequest.getServiceInstancesRequest().getRequestDetails().getRequestParameters();
773                 if(reqParam!=null && reqParam.isALaCarteSet() && recipe==null){
774                         return null;
775                 }else if (recipe == null) {  //aLaCarte wasn't sent, so we'll try the default
776                         serviceRecord = db.getServiceByModelName(defaultServiceModelName);
777                         recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name());
778                 }
779
780                 if(modelInfo.getModelVersionId() == null) {     
781                         modelInfo.setModelVersionId(serviceRecord.getModelUUID());
782                 }
783                 if(recipe==null){
784                         return null;
785                 }
786                 return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
787         }
788
789
790         private RecipeLookupResult getVnfOrVfModuleUri (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
791
792                 ModelInfo modelInfo = msoRequest.getModelInfo();
793                 String vnfComponentType = modelInfo.getModelType().name();
794
795                 RelatedInstanceList[] instanceList = null;
796                 if (msoRequest.getServiceInstancesRequest().getRequestDetails() != null) {
797                         instanceList = msoRequest.getServiceInstancesRequest().getRequestDetails().getRelatedInstanceList();
798                 }
799
800                 Recipe recipe = null;
801                 String defaultVnfType = msoRequest.getRequestInfo().getSource() + "_DEFAULT";
802                 String modelCustomizationId = modelInfo.getModelCustomizationId();
803                 String modelCustomizationName = modelInfo.getModelCustomizationName();
804                 String relatedInstanceModelVersionId = null;
805                 String relatedInstanceModelInvariantId = null;
806                 String relatedInstanceVersion = null;
807                 String relatedInstanceModelCustomizationName = null;
808
809                 if (instanceList != null) {
810
811                         for(RelatedInstanceList relatedInstanceList : instanceList){
812
813                                 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
814                                 ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
815                                 if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)){
816                                         relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
817                                         relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
818                                 }
819
820                                 if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)){
821                                         relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
822                                         relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId();
823                                         relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
824                                         relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName();
825                                 }
826                         }
827
828                         if(modelInfo.getModelType().equals(ModelType.vnf)) {
829                                 //                      a.      For a vnf request (only create, no update currently): 
830                                 //                              i.      (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in vnf_resource_customization.model_customization_uuid.
831                                 //                              ii.     (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or pre-v3), then modelInfo.modelCustomizationName must have 
832                                 //                                      been provided (else create request should be rejected).  APIH should use the relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName 
833                                 //                                      to â€œjoinâ€\9d service_to_resource_customizations with vnf_resource_customization to confirm a vnf_resource_customization.model_customization_uuid  record exists. 
834                                 //                              **If relatedInstance.modelInfo[service].modelVersionId  was not provided, use relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId 
835                                 //                                      (MODEL_UUID) in SERVICE table.
836                                 //                              iii.    Regardless of how the value was provided/obtained above, APIH must always populate vnfModelCustomizationId in bpmnRequest.  It would be assumed it was MSO generated 
837                                 //                                      during 1707 data migration if VID did not provide it originally on request.
838                                 //                              iv.     Note: continue to construct the â€œvnf-typeâ€\9d value and pass to BPMN (must still be populated in A&AI).  
839                                 //                              1.      If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to look it up in our catalog to construct vnf-type value to pass to BPMN.
840
841                                 VnfResource vnfResource = null;
842                                 VnfResourceCustomization vrc = null;
843                                 // Validation for vnfResource
844
845                                 if(modelCustomizationId!=null) {
846                                         vnfResource = db.getVnfResourceByModelCustomizationId(modelCustomizationId);
847                                 } else {
848                                         Service service = db.getServiceByModelUUID(relatedInstanceModelVersionId);
849                                         if(service == null) {
850                                                 service = db.getServiceByVersionAndInvariantId(relatedInstanceModelInvariantId, relatedInstanceVersion);
851                                         }
852
853                                 if(service == null) {
854                                         throw new ValidationException("service in relatedInstance");
855                                 }
856
857                                         vrc = db.getVnfResourceCustomizationByModelCustomizationName(modelCustomizationName, service.getModelUUID());
858                                         if(vrc != null) {
859                                                 vnfResource = vrc.getVnfResource();
860                                                 modelInfo.setModelCustomizationId(vrc.getModelCustomizationUuid());
861                                                 modelInfo.setModelCustomizationUuid(vrc.getModelCustomizationUuid());
862                                         }
863                                 }
864
865                                 if(vnfResource==null){
866                                         throw new ValidationException("catalog entry");
867                                 } else {
868                                         if(modelInfo.getModelVersionId() == null) {
869                                                 modelInfo.setModelVersionId(vnfResource.getModelUuid());
870                                         }
871                                 }
872
873                                 VnfRecipe vnfRecipe = db.getVnfRecipe(defaultVnfType, action.name());
874
875                                 if (vnfRecipe == null) {
876                                         return null;
877                                 }
878
879                                 return new RecipeLookupResult (vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
880                         } else {
881                                 //                      ii.     (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or pre-v3), then modelInfo.modelCustomizationName must have 
882                                 //                      been provided (else create request should be rejected).  APIH should use the relatedInstance.modelInfo[vnf].modelVersionId** + modelInfo[vnf].modelCustomizationName 
883                                 //                      to â€œjoinâ€\9d vnf_to_resource_customizations with vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid  record exists. 
884                                 //                      **If relatedInstance.modelInfo[vnf].modelVersionId  was not provided, use relatedInstance.modelInfo[vnf].modelInvariantId + modelVersion instead 
885                                 //                      to lookup modelVersionId (MODEL_UUID) in vnf_resource table. Once the vnf’s model_customization_uuid has been obtained, use it to find all vfModule customizations 
886                                 //                      for that vnf customization in the vnf_res_custom_to_vf_module_custom join table. For each vf_module_cust_model_customization_uuid value returned, 
887                                 //                      use that UUID to query vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId** to confirm record matches request data 
888                                 //                      (and to identify the modelCustomizationId associated with the vfModule in the request). **If modelInfo[vfModule|volumeGroup].modelVersionId was not 
889                                 //                      provided (potentially in v2/v3), use modelInfo[vfModule|volumeGroup].modelInvariantId + modelVersion instead. This means taking each record found 
890                                 //                      in vf_module_customization and looking up in vf_module (using vf_module_customization’s FK into vf_module) to find a match on MODEL_INVARIANT_UUID (modelInvariantId) 
891                                 //                      and MODEL_VERSION (modelVersion).
892
893                                 if(!msoRequest.getALaCarteFlag()) {
894                                         VfModuleCustomization vfmc = null;
895                                         VnfResourceCustomization vnfrc = null;
896                                         VfModule vfModule = null;
897
898                                         if( modelInfo.getModelCustomizationId() != null) {
899                                                 vfmc = db.getVfModuleCustomizationByModelCustomizationId(modelInfo.getModelCustomizationId());
900                                         } else {
901                                                 vnfrc =db.getVnfResourceCustomizationByVnfModelCustomizationNameAndModelVersionId(relatedInstanceModelCustomizationName, relatedInstanceModelVersionId);
902                                                 if(vnfrc == null) {
903                                                         vnfrc = db.getVnfResourceCustomizationByModelInvariantId(relatedInstanceModelInvariantId, relatedInstanceVersion, relatedInstanceModelCustomizationName);
904                                                 } 
905
906                                                 List<VfModuleCustomization> list = db.getVfModuleCustomizationByVnfModuleCustomizationUuid(vnfrc.getModelCustomizationUuid());
907
908                                                 String vfModuleModelUUID = modelInfo.getModelVersionId();
909                                                 for(VfModuleCustomization vf : list) {
910                                                         if(vfModuleModelUUID != null) {
911                                                                 vfModule = db.getVfModuleByModelCustomizationIdAndVersion(vf.getModelCustomizationUuid(), vfModuleModelUUID);
912                                                         } else {
913                                                                 vfModule = db.getVfModuleByModelCustomizationIdModelVersionAndModelInvariantId(vf.getModelCustomizationUuid(), modelInfo.getModelVersion(), modelInfo.getModelInvariantId());
914                                                         }
915
916                                                         if(vfModule != null) {
917                                                                 modelInfo.setModelCustomizationId(vf.getModelCustomizationUuid());
918                                                                 modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUuid());
919                                                                 break;
920                                                         }
921                                                 }
922                                         }
923
924                                         if(vfmc == null && vfModule == null) {
925                                                 throw new ValidationException("no catalog entry found");
926                                         } else if (vfModule == null && vfmc != null) {
927                                                 vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in VfModuleCustomization table
928                                         }
929
930                                         if(modelInfo.getModelVersionId() == null) {
931                                                 modelInfo.setModelVersionId(vfModule.getModelUUID());
932                                         }
933                                         recipe = db.getVnfComponentsRecipeByVfModuleModelUUId(vfModule.getModelUUID(), vnfComponentType, action.name());
934                                 } 
935
936                                 if(recipe == null) {
937                                         recipe = db.getVnfComponentsRecipeByVfModuleModelUUId(defaultVnfType, vnfComponentType, action.name());
938                                         if (recipe == null) { 
939                                                 recipe = db.getVnfComponentsRecipeByVfModuleModelUUId("*", vnfComponentType, action.name());
940                                         }
941
942                                         if(recipe == null) {
943                                                 return null;
944                                         }
945                                 }
946                         }
947                 } else {
948                         msoLogger.debug("recipe is null, getting default");
949
950                         if(modelInfo.getModelType().equals(ModelType.vnf)) {
951                                 recipe = db.getVnfRecipe(defaultVnfType, action.name());
952                                 if (recipe == null) {
953                                         return null;
954                                 }
955                         } else {
956                                 recipe = db.getVnfComponentsRecipeByVfModuleModelUUId("VID_DEFAULT", vnfComponentType, action.name());
957
958                                 if (recipe == null) {
959                                         return null;
960                                 }
961                         }
962                 }
963
964                 return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
965         }
966
967         private RecipeLookupResult getNetworkUri (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
968
969                 String defaultNetworkType = msoRequest.getRequestInfo().getSource() + "_DEFAULT";
970
971                 ModelInfo modelInfo = msoRequest.getModelInfo();
972                 String modelName = modelInfo.getModelName();
973                 Recipe recipe = null;
974                 if(msoRequest.getALaCarteFlag()){
975                         recipe = db.getNetworkRecipe(defaultNetworkType, action.name());
976                 }else{
977                         if(modelInfo.getModelCustomizationId()!=null){
978                                 NetworkResource networkResource = db.getNetworkResourceByModelCustUuid(modelInfo.getModelCustomizationId());
979                                 if(networkResource!=null){
980                                         if(modelInfo.getModelVersionId() == null) {
981                                                 modelInfo.setModelVersionId(networkResource.getModelUUID());
982                                         }
983                                         recipe = db.getNetworkRecipe(networkResource.getModelName(), action.name());
984                                 }else{
985                                         throw new ValidationException("no catalog entry found");
986                                 }
987                         }else{
988                                 //ok for version < 3 and action delete
989                                 recipe = db.getNetworkRecipe(modelName, action.name());
990                         }
991                         if(recipe == null){
992                                 recipe = db.getNetworkRecipe(defaultNetworkType, action.name());
993                         }
994                 }
995                 if (recipe == null) {
996                         return null;
997                 }
998                 return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
999         }
1000 }