Merge "Swap if statement with switch"
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / VnfRequestHandler.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
21 package org.openecomp.mso.apihandlerinfra;
22
23
24 import java.io.StringReader;
25 import java.io.StringWriter;
26 import java.util.LinkedList;
27 import java.util.List;
28 import java.util.UUID;
29
30 import javax.ws.rs.GET;
31 import javax.ws.rs.POST;
32 import javax.ws.rs.Path;
33 import javax.ws.rs.PathParam;
34 import javax.ws.rs.Produces;
35 import javax.ws.rs.QueryParam;
36 import javax.ws.rs.core.Context;
37 import javax.ws.rs.core.MediaType;
38 import javax.ws.rs.core.Response;
39 import javax.ws.rs.core.UriInfo;
40 import javax.xml.bind.JAXBContext;
41 import javax.xml.bind.JAXBException;
42 import javax.xml.bind.Marshaller;
43
44 import org.apache.http.HttpResponse;
45 import org.apache.http.HttpStatus;
46
47 import javax.xml.bind.Unmarshaller;
48 import javax.xml.transform.sax.SAXSource;
49
50 import org.xml.sax.InputSource;
51
52 import org.openecomp.mso.apihandler.common.ErrorNumbers;
53 import org.openecomp.mso.apihandler.common.RequestClient;
54 import org.openecomp.mso.apihandler.common.RequestClientFactory;
55 import org.openecomp.mso.apihandler.common.ResponseHandler;
56 import org.openecomp.mso.apihandler.common.ValidationException;
57 import org.openecomp.mso.apihandlerinfra.vnfbeans.ActionType;
58 import org.openecomp.mso.apihandlerinfra.vnfbeans.ObjectFactory;
59 import org.openecomp.mso.apihandlerinfra.vnfbeans.RequestInfo;
60 import org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType;
61 import org.openecomp.mso.apihandlerinfra.vnfbeans.VnfInputs;
62 import org.openecomp.mso.apihandlerinfra.vnfbeans.VnfOutputs;
63 import org.openecomp.mso.apihandlerinfra.vnfbeans.VnfRequest;
64 import org.openecomp.mso.apihandlerinfra.vnfbeans.VnfRequests;
65 import org.openecomp.mso.db.catalog.CatalogDatabase;
66 import org.openecomp.mso.db.catalog.beans.Recipe;
67 import org.openecomp.mso.db.catalog.beans.VfModule;
68 import org.openecomp.mso.db.catalog.beans.VnfResource;
69 import org.openecomp.mso.logger.MessageEnum;
70 import org.openecomp.mso.logger.MsoAlarmLogger;
71 import org.openecomp.mso.logger.MsoLogger;
72 import org.openecomp.mso.properties.MsoJavaProperties;
73 import org.openecomp.mso.properties.MsoPropertiesFactory;
74 import org.openecomp.mso.requestsdb.InfraRequests;
75 import org.openecomp.mso.requestsdb.InfraActiveRequests;
76 import org.openecomp.mso.requestsdb.RequestsDatabase;
77 import org.openecomp.mso.utils.UUIDChecker;
78
79 @Path("/{version: v1|v2|v3}/vnf-request")
80 public class VnfRequestHandler {
81
82     @Context
83     private UriInfo uriInfo;
84
85     protected ObjectFactory beansObjectFactory = new ObjectFactory ();
86
87     public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
88
89     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
90
91     private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
92
93     private static MsoJavaProperties props = MsoPropertiesUtils.loadMsoProperties ();
94
95     private static final String NOT_FOUND = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Application Not Started</title></head><body>Application not started, properties file missing or invalid or Database Connection failed</body></html>";
96
97     private static final Response NOT_STARTED_RESPONSE = Response.status (HttpStatus.SC_SERVICE_UNAVAILABLE)
98             .entity (NOT_FOUND)
99             .build ();
100     private RequestsDatabase requestDB = RequestsDatabase.getInstance();
101     
102     @GET
103     public Response queryFilters (@QueryParam("vnf-type") String vnfType,
104                                   @QueryParam("service-type") String serviceType,
105                                   @QueryParam("aic-node-clli") String aicNodeClli,
106                                   @QueryParam("tenant-id") String tenantId,
107                                   @QueryParam("volume-group-id") String volumeGroupId,
108                                   @QueryParam("volume-group-name") String volumeGroupName,
109                                   @QueryParam("vnf-name") String vnfName,
110                                   @PathParam("version") String version) {
111         long startTime = System.currentTimeMillis ();
112         MsoLogger.setServiceName ("VNFQueryFilters");
113         // Generate a Request Id
114         UUIDChecker.generateUUID(msoLogger);
115         msoLogger.debug ("Incoming request received for queryFilter with vnf-type:" + vnfType
116                                                                 + " service-type:" + serviceType
117                                                                 + " aic-node-clli:" + aicNodeClli
118                                                                 + " tenant-id:" + tenantId
119                                                                 + " volume-group-id:" + volumeGroupId
120                                                                 + " volume-group-name:" + volumeGroupName
121                                                                 + " vnf-name: " + vnfName);
122         Response response = null;
123         if (vnfType != null) {
124             response = this.getRequestList ("vnfType", vnfType, version);
125         } else {
126             response = queryGenericFilters (serviceType, aicNodeClli, tenantId, volumeGroupId, volumeGroupName, vnfName, version);
127         }
128         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful");
129         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
130         return response;
131     }
132
133     @GET
134     @Path(Constants.REQUEST_ID_PATH)
135     public Response getRequest (@PathParam("request-id") String requestId, @PathParam("version") String version) {
136         // Check INFRA_ACTIVE_REQUESTS table to find info
137         // on this request
138         long startTime = System.currentTimeMillis ();
139         MsoLogger.setServiceName ("VNFGetRequest");
140         // Generate a Request Id
141         UUIDChecker.generateUUID(msoLogger);
142         msoLogger.debug ("Incoming request received for getRequest with request-id:" + requestId + ", version = " + version);
143
144         Response response = getRequestGeneric (requestId, version);
145         msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful");
146         msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
147         return response;
148     }
149
150     protected MsoLogger getMsoLogger () {
151         return msoLogger;
152     }
153
154     protected String getRequestType () {
155         return VnfRequestType.VNF.toString ();
156     }
157
158     protected void fillVnfRequest (VnfRequest qr, InfraRequests ar, String version) {
159         VnfInputs vi = beansObjectFactory.createVnfInputs ();
160
161         if (ar.getVnfId () != null) {
162             vi.setVnfId (ar.getVnfId ());
163         }
164         if (ar.getVnfName () != null) {
165             vi.setVnfName (ar.getVnfName ());
166         }
167         if (ar.getVnfType () != null) {
168             vi.setVnfType (ar.getVnfType ());
169         }        
170         if (ar.getTenantId () != null) {
171             vi.setTenantId (ar.getTenantId ());
172         }
173         if (ar.getProvStatus () != null) {
174             vi.setProvStatus (ar.getProvStatus ());
175         }
176         if (ar.getVolumeGroupName () != null) {
177                 vi.setVolumeGroupName (ar.getVolumeGroupName ());
178         }
179         if (ar.getVolumeGroupId () != null) {
180                 vi.setVolumeGroupId (ar.getVolumeGroupId ());
181         }
182         switch (version) {
183             case Constants.SCHEMA_VERSION_V1:
184                 if (ar.getServiceType() != null) {
185                     vi.setServiceType(ar.getServiceType());
186                 }
187                 if (ar.getAicNodeClli() != null) {
188                     vi.setAicNodeClli(ar.getAicNodeClli());
189                 }
190                 break;
191             case Constants.SCHEMA_VERSION_V2:
192                 if (ar.getAaiServiceId() != null) {
193                     vi.setServiceId(ar.getAaiServiceId());
194                 }
195                 if (ar.getAicCloudRegion() != null) {
196                     vi.setAicCloudRegion(ar.getAicCloudRegion());
197                 }
198                 if (ar.getVfModuleName() != null) {
199                     vi.setVfModuleName(ar.getVfModuleName());
200                 }
201                 if (ar.getVfModuleId() != null) {
202                     vi.setVfModuleId(ar.getVfModuleId());
203                 }
204                 if (ar.getVfModuleModelName() != null) {
205                     vi.setVfModuleModelName(ar.getVfModuleModelName());
206                 }
207                 break;
208             case Constants.SCHEMA_VERSION_V3:
209                 if (ar.getAaiServiceId() != null) {
210                     vi.setServiceId(ar.getAaiServiceId());
211                 }
212                 if (ar.getAicCloudRegion() != null) {
213                     vi.setAicCloudRegion(ar.getAicCloudRegion());
214                 }
215                 if (ar.getVfModuleName() != null) {
216                     vi.setVfModuleName(ar.getVfModuleName());
217                 }
218                 if (ar.getVfModuleId() != null) {
219                     vi.setVfModuleId(ar.getVfModuleId());
220                 }
221                 if (ar.getVfModuleModelName() != null) {
222                     vi.setVfModuleModelName(ar.getVfModuleModelName());
223                 }
224                 if (ar.getServiceInstanceId() != null) {
225                     vi.setServiceInstanceId(ar.getServiceInstanceId());
226                 }
227                 break;
228         }
229         qr.setVnfInputs (vi);
230
231         qr.setVnfParams (ar.getVnfParams ());
232
233         try {
234             String vnfoutputs = ar.getVnfOutputs ();
235             if (vnfoutputs != null && vnfoutputs.length () > 0) {
236                 msoLogger.debug ("Read VNF outputs: " + vnfoutputs);
237                 VnfOutputs vnfOutput = null;
238
239                 // Now unmarshal it into vnf outputs
240                 try {
241                     JAXBContext jaxbContext = JAXBContext.newInstance (VnfOutputs.class);
242                     Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller ();
243
244                     InputSource inputSource = new InputSource (new StringReader (vnfoutputs));
245                     SAXSource source = new SAXSource (inputSource);
246
247                     vnfOutput = jaxbUnmarshaller.unmarshal (source, VnfOutputs.class).getValue ();
248
249                 } catch (Exception e) {
250                     msoLogger.debug ("Validation failed", e);
251                     throw new ValidationException ("format for vnf outputs");
252                 }
253
254                 qr.setVnfOutputs (vnfOutput);
255             }
256         } catch (Exception e) {
257             msoLogger.debug ("exception reading vnfOutputs Clob", e);
258         }
259     }
260
261     protected Response queryGenericFilters (String serviceType, String aicNodeClli, String tenantId, String volumeGroupId, String volumeGroupName, String vnfName, String version) {
262         if (serviceType != null) {
263             return this.getRequestList ("serviceType", serviceType, version);
264         }
265         if (aicNodeClli != null) {
266             return this.getRequestList ("aicNodeClli", aicNodeClli, version);
267         }
268         if (tenantId != null) {
269             return this.getRequestList ("tenantId", tenantId, version);
270         }
271         if (volumeGroupId != null) {
272                 return this.getRequestList ("volumeGroupId", volumeGroupId, version);
273         }
274         if (volumeGroupName != null) {
275                 return this.getRequestList ("volumeGroupName", volumeGroupName, version);
276         }
277         if (vnfName != null) {
278                 return this.getRequestList ("vnfName", vnfName, version);
279         }
280         return Response.status (HttpStatus.SC_BAD_REQUEST).entity ("").build ();
281     }
282
283     protected Response getRequestGeneric (String requestId, String version) {
284         // Check INFRA_ACTIVE_REQUESTS table to find info
285         // on this request
286
287         getMsoLogger ().debug ("getRequest: " + requestId);
288
289         String responseString = null;
290
291         InfraActiveRequests activeReq = requestDB.getRequestFromInfraActive (requestId, getRequestType ());
292         if (activeReq != null) {
293             // build response for active
294             responseString = infraRequestsResponse (activeReq, version);
295             return Response.status (HttpStatus.SC_OK).entity (responseString).build ();
296         } else {
297             // Report that no request has been found
298             return Response.status (HttpStatus.SC_NOT_FOUND).entity ("").build ();
299         }
300     }
301
302     protected Response getRequestList (String queryAttribute, String queryValue, String version) {
303         // Check INFRA_ACTIVE_REQUESTS table to find info
304         // on this request
305
306         getMsoLogger ().debug ("getRequest based on " + queryAttribute + ": " + queryValue);
307
308         List <InfraActiveRequests> activeReqList = requestDB.getRequestListFromInfraActive (queryAttribute,
309                                                                                                    queryValue,
310                                                                                                    getRequestType ());
311
312         List <VnfRequest> queryResponseList = new LinkedList<>();
313
314         if (activeReqList != null) {
315             // build response for active
316             queryResponseList = infraRequestsResponses (activeReqList, version);
317
318         }
319
320         if (queryResponseList != null && !queryResponseList.isEmpty ()) {
321             String result = this.translateVnfRequests (queryResponseList);
322             return Response.status (HttpStatus.SC_OK).entity (result).build ();
323
324         } else {
325             // Report that no request has been found
326             return Response.status (HttpStatus.SC_NOT_FOUND).entity ("").build ();
327         }
328     }
329
330     private VnfRequest fillGeneric (InfraRequests ar) {
331         VnfRequest qr = beansObjectFactory.createVnfRequest ();
332         RequestInfo ri = beansObjectFactory.createRequestInfo ();
333         ri.setRequestId (ar.getRequestId ());
334         ri.setAction (ActionType.fromValue (ar.getAction ()));
335         ri.setRequestStatus (RequestStatusType.fromValue (ar.getRequestStatus ()));
336         if (ar.getProgress () != null) {
337             ri.setProgress (ar.getProgress ().intValue ());
338         }
339         if (ar.getSource () != null) {
340             ri.setSource (ar.getSource ());
341         }
342
343         ri.setStartTime (ar.getStartTime ().toString ());
344         if (ar.getEndTime () != null) {
345             ri.setEndTime (ar.getEndTime ().toString ());
346         }
347
348         if (ar.getStatusMessage () != null) {
349             ri.setStatusMessage (ar.getStatusMessage ());
350         }
351         qr.setRequestInfo (ri);
352         return qr;
353     }
354
355     private List <VnfRequest> infraRequestsResponses (List <? extends InfraRequests> arList, String version) {
356         List <VnfRequest> queryResponseList = new LinkedList<>();
357
358         for (InfraRequests ar : arList) {
359             VnfRequest qr = fillGeneric (ar);
360             fillVnfRequest (qr, ar, version);
361             queryResponseList.add (qr);
362         }
363         return queryResponseList;
364     }
365
366     private String translateVnfRequests (List <VnfRequest> queryResponseList) {
367         VnfRequests queryResponses = new VnfRequests ();
368         for (VnfRequest aQueryResponseList : queryResponseList) {
369             queryResponses.getVnfRequest().add(aQueryResponseList);
370         }
371
372         StringWriter stringWriter = new StringWriter ();
373         try {
374             JAXBContext jaxbContext = JAXBContext.newInstance (VnfRequests.class);
375             Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
376
377             // output pretty printed
378             jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
379
380             jaxbMarshaller.marshal (queryResponses, stringWriter);
381
382         } catch (JAXBException e) {
383             getMsoLogger ().debug ("Marshalling issue", e);
384         }
385
386         return stringWriter.toString ();
387     }
388
389     private String infraRequestsResponse (InfraRequests ar, String version) {
390         VnfRequest qr = fillGeneric (ar);
391         fillVnfRequest (qr, ar, version);
392
393         StringWriter stringWriter = new StringWriter ();
394         try {
395             JAXBContext jaxbContext = JAXBContext.newInstance (VnfRequest.class);
396             Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
397
398             jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
399             jaxbMarshaller.marshal (qr, stringWriter);
400
401         } catch (JAXBException e) {
402             getMsoLogger ().debug ("Marshalling issue", e);
403         }
404
405         String response = stringWriter.toString ();
406         return response;
407     }
408
409     @POST
410     @Path("/")
411     @Produces(MediaType.APPLICATION_XML)
412     public Response manageVnfRequest (String reqXML, @PathParam("version") String version) {
413         MsoLogger.setServiceName ("VnfRequest");
414         if ("v1".equals(version)) {
415             return manageVnfRequestImpl (reqXML, Constants.SCHEMA_VERSION_V1);
416         } else if ("v2".equals(version)) {
417             return manageVnfRequestImpl (reqXML, Constants.SCHEMA_VERSION_V2);
418         } else if ("v3".equals(version)) {
419             return manageVnfRequestImpl (reqXML, Constants.SCHEMA_VERSION_V3);
420         } else {
421             long startTime = System.currentTimeMillis ();
422             msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "Version not found");
423                 return Response.status(HttpStatus.SC_NOT_FOUND).build();
424         }
425     }
426     
427     private Response manageVnfRequestImpl (String reqXML, String version) {
428         String methodName = "VnfRequest";
429         props = MsoPropertiesUtils.loadMsoProperties ();
430         long startTime = System.currentTimeMillis ();
431
432         // Generate unique request id for the new request
433         UUID requestUUID = UUID.randomUUID ();
434
435         VnfMsoInfraRequest msoRequest = new VnfMsoInfraRequest (requestUUID.toString ());
436         MsoLogger.setLogContext (msoRequest.getRequestId (), null);
437
438         if (MsoPropertiesUtils.getNoPropertiesState()) {
439             msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.ServiceNotAvailable, "Exiting the transaction: Infra API Handler not started, properties file missing or invalid");
440             return NOT_STARTED_RESPONSE;
441         }
442
443         uriInfo.getRequestUri ();
444
445         if (reqXML == null) {
446             msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.BadRequest, "The content of the request is null");
447             return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build ();
448         }
449
450         String requestUri = uriInfo.getRequestUri ().toString ();
451         msoLogger.debug ("Incoming request received for pose VNFRequest:" + reqXML);
452
453         msoRequest.setRequestUri (requestUri);
454         msoLogger.debug ("Schema version: " + version);
455         try {
456             msoRequest.parse (reqXML, version, props);
457         } catch (Exception e) {
458             msoLogger.debug ("Validation failed: ", e);
459             msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
460             Response response = msoRequest.buildResponseFailedValidation (HttpStatus.SC_BAD_REQUEST, e.getMessage ());
461             if (msoRequest.getRequestId () != null) {
462                 msoLogger.debug ("Logging failed message to the database");
463                 msoRequest.createRequestRecord (Status.FAILED);
464             }
465             msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, reqXML, "", "", MsoLogger.ErrorCode.SchemaError, "Exception when parsing reqXML", e);
466             msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Validation of the input request failed");
467             msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
468             return response;
469         }
470         MsoLogger.setServiceName (MsoLogger.getServiceName () + "_" + msoRequest.getRequestInfo().getAction().name());
471         msoLogger.debug ("Update serviceName with detailed action info to:" + MsoLogger.getServiceName () + "_" + msoRequest.getRequestInfo().getAction().name());
472         if (msoRequest.getRequestInfo ().getAction () == org.openecomp.mso.apihandlerinfra.vnfbeans.ActionType.CREATE) {
473             // Check if this request is a duplicate of the one with the same vnfName
474             msoLogger.debug ("Checking for a duplicate with the same vnf-name");
475             InfraActiveRequests dup = null;
476             try {
477                 dup = requestDB.checkDuplicateByVnfName (msoRequest.getVnfInputs ().getVnfName (),
478                                                                 msoRequest.getRequestInfo ().getAction ().value (),
479                                                                 "VNF");
480
481             } catch (Exception e) {
482                 msoLogger.debug ("Exception", e);
483                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
484                 Response response = msoRequest.buildResponseWithError (HttpStatus.SC_INTERNAL_SERVER_ERROR,
485                                                                        ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB,
486                                                                        null,
487                                                                        e.getMessage ());
488                 alarmLogger.sendAlarm ("MsoDatabaseAccessError",
489                                        MsoAlarmLogger.CRITICAL,
490                                        Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB));
491                 msoRequest.createRequestRecord (Status.FAILED);
492                 msoLogger.error (MessageEnum.APIH_DUPLICATE_CHECK_EXC_ATT, "vnf-name", "", "", MsoLogger.ErrorCode.DataError, "Exception while checking for duplicated request", e);
493                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while checking for duplicated request");
494                 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
495                 return response;
496             }
497             if (dup != null) {
498                 // Found the duplicate record. Return the appropriate error.
499                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
500                 Response response = msoRequest.buildResponse (HttpStatus.SC_CONFLICT,
501                                                               ErrorNumbers.LOCKED_CREATE_ON_THE_SAME_VNF_NAME_IN_PROGRESS,
502                                                               dup);
503                 msoLogger.warn (MessageEnum.APIH_DUPLICATE_FOUND, "CREATE on the same VNF Name is already progress", "", "", MsoLogger.ErrorCode.DataError, "Duplicates request - CREATE on the same VNF Name is already progress");
504                 msoRequest.createRequestRecord (Status.FAILED);
505                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, "Duplicates request - CREATE on the same VNF Name is already progress");
506                 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
507                 return response;
508             }
509         } else {
510             // Check if this request is a duplicate of the one with the same vnfId
511             InfraActiveRequests dup = null;
512             msoLogger.debug ("Checking for a duplicate with the same vnf-id");
513             try {
514                 dup = requestDB.checkDuplicateByVnfId (msoRequest.getVnfInputs ().getVnfId (),
515                                                               msoRequest.getRequestInfo ().getAction ().value (),
516                                                               "VNF");
517
518             } catch (Exception e) {
519                 msoLogger.debug ("Exception", e);
520                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
521                 Response response = msoRequest.buildResponseWithError (HttpStatus.SC_INTERNAL_SERVER_ERROR,
522                                                                        ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB,
523                                                                        null,
524                                                                        e.getMessage ());
525                 alarmLogger.sendAlarm ("MsoDatabaseAccessError",
526                                        MsoAlarmLogger.CRITICAL,
527                                        Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB));
528                 msoRequest.createRequestRecord (Status.FAILED);
529                 msoLogger.error (MessageEnum.APIH_DUPLICATE_CHECK_EXC_ATT, "vnf-id", "", "", MsoLogger.ErrorCode.DataError, "Exception while checking for a duplicate request with the same vnf-id", e);
530                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while checking for a duplicate request with the same vnf-id");
531                 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
532                 return response;
533             }
534             if (dup != null) {
535                 // Found the duplicate record. Return the appropriate error.
536                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
537                 Response response = msoRequest.buildResponse (HttpStatus.SC_CONFLICT,
538                                                               ErrorNumbers.LOCKED_SAME_ACTION_AND_VNF_ID,
539                                                               dup);
540                 msoLogger.warn (MessageEnum.APIH_DUPLICATE_FOUND,
541                                 msoRequest.getRequestInfo ().getAction ().value ()
542                                                                   + " on the same VNF Id already in progress", "", "", MsoLogger.ErrorCode.DataError, "Duplicated request on the same VNF Id already in progress");
543
544                 msoRequest.createRequestRecord (Status.FAILED);
545                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, "Duplicated request on the same VNF Id already in progress");
546                 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
547                 return response;
548             }
549         }
550
551         String orchestrationURI = "";
552
553         // Query MSO Catalog DB
554         try (CatalogDatabase db = CatalogDatabase.getInstance()){
555
556             Recipe recipe = null;
557
558             if (version.equals(Constants.SCHEMA_VERSION_V1)) {
559                 // First get recipe for the service type given
560                 if (msoRequest.getServiceType () != null
561                         && msoRequest.getServiceType ().length () > 0) {
562                     recipe = db.getVnfRecipe (msoRequest.getVnfInputs ().getVnfType (),
563                             msoRequest.getRequestInfo ().getAction ().value (),
564                             msoRequest.getServiceType ());
565                 }
566                 // If no recipe for the service type or no service type was given, look for recipe without service type
567                 if (recipe == null) {
568                     recipe = db.getVnfRecipe (msoRequest.getVnfInputs ().getVnfType (),
569                             msoRequest.getRequestInfo ().getAction ().value (),
570                             null);
571                 }
572             }
573             if (version.equals (Constants.SCHEMA_VERSION_V2) || version.equals (Constants.SCHEMA_VERSION_V3)) {
574                 switch (msoRequest.getRequestInfo ().getAction ()) {
575                     case CREATE:
576                     case UPDATE:
577                     case DELETE:
578                         // First get recipe for the vnf type given
579                         recipe = db.getVnfRecipe (msoRequest.getVnfInputs ().getVnfType (),
580                                 msoRequest.getRequestInfo ().getAction ().value ());
581
582                         // If no recipe for the vnf type is found, look for generic recipe with "*" vnf type
583                         if (recipe == null) {
584                             recipe = db.getVnfRecipe (Constants.VNF_TYPE_WILDCARD,
585                                     msoRequest.getRequestInfo ().getAction ().value ());
586                         }
587                         break;
588                     case CREATE_VF_MODULE:
589                     case UPDATE_VF_MODULE:
590                     case DELETE_VF_MODULE:
591                         // First get recipe for the vnf type/vf module model name through vf module id query
592                         recipe = db.getVfModuleRecipe (msoRequest.getVnfInputs ().getVnfType (), msoRequest.getVnfInputs ().getVfModuleModelName (),
593                                 msoRequest.getRequestInfo ().getAction ().value ());
594
595                         // If no recipe is found, look for generic recipe with "*" vnf type
596                         if (recipe == null) {
597                             recipe = db.getVnfRecipeByVfModuleId (msoRequest.getVnfInputs ().getVfModuleId (),
598                                     Constants.VNF_TYPE_WILDCARD, msoRequest.getRequestInfo ().getAction ().value ());
599                         }
600                         // First get recipe for the vnf type given
601                         //recipe = db.getVnfRecipe (msoRequest.getVnfInputs ().getVnfType (),
602                         //      msoRequest.getRequestInfo ().getAction ().value ());
603
604                         // If no recipe for the vnf type is found, look for generic recipe with "*" vnf type
605                         //if (recipe == null) {
606                         //      recipe = db.getVnfRecipe (Constants.VNF_TYPE_WILDCARD,
607                         //                      msoRequest.getRequestInfo ().getAction ().value ());
608                         //
609                         //}
610                         break;
611                     default:
612                         break;
613                 }
614
615             }
616
617             if (recipe == null) {
618                 msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, "VNF Recipe", "", "", MsoLogger.ErrorCode.DataError, "No recipe found in DB");
619                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
620                 Response response = msoRequest.buildResponseWithError (HttpStatus.SC_NOT_FOUND,
621                         ErrorNumbers.RECIPE_DOES_NOT_EXIST,
622                         null,
623                         "");
624                 msoRequest.createRequestRecord (Status.FAILED);
625                 db.close ();
626                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No recipe found in DB");
627                 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
628                 return response;
629             }
630             orchestrationURI = recipe.getOrchestrationUri ();
631             msoLogger.debug ("Orchestration URI is: " + orchestrationURI);
632
633             // Retrieve additional info for Vf Modules from Catalog DB to send it to BPMN
634             switch (msoRequest.getRequestInfo ().getAction ()) {
635                 case CREATE_VF_MODULE:
636                 case UPDATE_VF_MODULE:
637                     String personaModelId = "";
638                     String personaModelVersion = "";
639                     String vnfPersonaModelId = "";
640                     String vnfPersonaModelVersion = "";
641                     Boolean isBase = false;
642                     String asdcServiceModelVersion = msoRequest.getVnfInputs ().getAsdcServiceModelVersion ();
643
644                     // Get VF Module-specific persona info and base module indicator
645                     VfModule vfm = null;
646                     String vfModuleType = msoRequest.getVnfInputs ().getVnfType () + "::" + msoRequest.getVnfInputs ().getVfModuleModelName ();
647                     if (asdcServiceModelVersion != null && !asdcServiceModelVersion.isEmpty ()) {
648                         vfm = db.getVfModuleType (vfModuleType, asdcServiceModelVersion);
649                     }
650                     else {
651                         vfm = db.getVfModuleType (vfModuleType);
652                     }
653                     if (vfm != null) {
654                         if (vfm.getIsBase() == 1) {
655                             isBase = true;
656                         }
657                         personaModelId = vfm.getModelInvariantUuid();
658                         personaModelVersion = vfm.getModelVersion();
659                         msoLogger.debug("Setting personaModelId to " + personaModelId +
660                                 ", personaModelVersion to " + personaModelVersion);
661                     }
662                     // Get VNF-specific persona info
663                     VnfResource vnfr = null;
664                     if (asdcServiceModelVersion != null && !asdcServiceModelVersion.isEmpty ()) {
665                         vnfr = db.getVnfResource (msoRequest.getVnfInputs ().getVnfType (), asdcServiceModelVersion);
666                     }
667                     else {
668                         vnfr = db.getVnfResource (msoRequest.getVnfInputs ().getVnfType ());
669                     }
670                     if (vnfr != null) {
671                         vnfPersonaModelId = vnfr.getModelInvariantUuid ();
672                         vnfPersonaModelVersion = vnfr.getModelVersion();
673                         msoLogger.debug("Setting vnfPersonaModelId to " + vnfPersonaModelId +
674                                 ", vnfPersonaModelVersion to " + vnfPersonaModelVersion);
675                     }
676
677                     msoRequest.addBPMNSpecificInputs(personaModelId, personaModelVersion, isBase,
678                             vnfPersonaModelId, vnfPersonaModelVersion);
679
680                     break;
681                 default:
682                     break;
683             }
684
685             db.close ();
686
687             String requestId = msoRequest.getRequestId ();
688             msoLogger.debug ("requestId is: " + requestId);
689             msoLogger.debug ("About to insert a record");
690
691             try {
692                 msoRequest.createRequestRecord (Status.PENDING);
693             } catch (Exception e) {
694                 msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC_REASON, "Exception while creating record in DB", "", "", MsoLogger.ErrorCode.SchemaError, "Exception while creating record in DB", e);
695                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
696                 Response response = msoRequest.buildResponseWithError (HttpStatus.SC_INTERNAL_SERVER_ERROR,
697                         ErrorNumbers.COULD_NOT_WRITE_TO_REQUESTS_DB,
698                         null,
699                         "non-unique request-id specified");
700                 // Cannot create a record of this request here, our communication with MSO DB just failed. Do not try
701                 // to create a failed record
702                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while creating record in DB");
703                 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
704                 return response;
705             }
706
707             msoLogger.debug("Request going to BPEL: " + msoRequest.getRequestXML ());
708
709             RequestClient requestClient = null;
710             HttpResponse response = null;
711             long subStartTime = System.currentTimeMillis();
712             try {
713                 requestClient = RequestClientFactory.getRequestClient (orchestrationURI, props);
714                 // Capture audit event
715                 msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ());
716                 response = requestClient.post(msoRequest.getRequestXML(),
717                     requestId,
718                     Integer.toString(recipe.getRecipeTimeout()),
719                     version,
720                     null,
721                     null);
722                 msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", orchestrationURI, null);
723             } catch (Exception e) {
724                 msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", orchestrationURI, null);
725                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
726                 Response resp = msoRequest.buildResponseWithError (HttpStatus.SC_BAD_GATEWAY,
727                         ErrorNumbers.NO_COMMUNICATION_TO_BPEL,
728                         null,
729                         e.getMessage ());
730                 alarmLogger.sendAlarm ("MsoConfigurationError",
731                         MsoAlarmLogger.CRITICAL,
732                         Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
733                 msoRequest.updateFinalStatus (Status.FAILED);
734                 msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, "Camunda", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine", e);
735                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine");
736                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
737                 return resp;
738             }
739
740             if (response == null) {
741                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
742                 Response resp = msoRequest.buildResponseWithError (HttpStatus.SC_BAD_GATEWAY,
743                         ErrorNumbers.NO_RESPONSE_FROM_BPEL,
744                         null,
745                         "bpelResponse is null");
746                 msoRequest.updateFinalStatus (Status.FAILED);
747                 msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, "Null response from BPEL", "Camunda", "", MsoLogger.ErrorCode.AvailabilityError, "Null response from BPEL");
748                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Null response from BPMN");
749                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
750                 return resp;
751             }
752
753             ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
754             int bpelStatus = respHandler.getStatus ();
755
756             // BPEL accepted the request, the request is in progress
757             if (bpelStatus == HttpStatus.SC_ACCEPTED) {
758                 String bpelXMLResponseBody = respHandler.getResponseBody ();
759                 msoLogger.debug ("Received from BPEL: " + bpelXMLResponseBody);
760                 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.IN_PROGRESS);
761                 requestDB.updateInfraStatus (msoRequest.getRequestId (),
762                         Status.IN_PROGRESS.toString (),
763                         Constants.PROGRESS_REQUEST_IN_PROGRESS,
764                         Constants.MODIFIED_BY_APIHANDLER);
765                 Response resp = msoRequest.buildResponse (bpelStatus, null, null);
766                 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN accepted the request, the request is in progress");
767                 msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
768                 return resp;
769             } else {
770
771                 String bpelXMLResponseBody = respHandler.getResponseBody ();
772                 if (bpelXMLResponseBody != null && !bpelXMLResponseBody.isEmpty ()) {
773                     msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
774                     Response resp = msoRequest.buildResponse (bpelStatus, bpelXMLResponseBody, null);
775                     msoRequest.updateFinalStatus (Status.FAILED);
776                     msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR,
777                             "Response from BPEL engine is failed with HTTP Status=" + bpelStatus, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is failed with HTTP Status=" + bpelStatus);
778                     msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPMN engine is failed");
779                     msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
780                     return resp;
781                 } else {
782                     msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
783                     Response resp = msoRequest.buildResponse (bpelStatus, ErrorNumbers.ERROR_FROM_BPEL, null);
784                     msoRequest.updateFinalStatus (Status.FAILED);
785                     msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, "Response from BPEL engine is empty", "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty");
786                     msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPEL engine is empty");
787                     msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
788                     return resp;
789                 }
790             }
791         } catch (Exception e) {
792             msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
793             msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
794             Response response = msoRequest.buildResponseWithError (HttpStatus.SC_NOT_FOUND,
795                                                                    ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB,
796                                                                    null,
797                                                                    e.getMessage ());
798             alarmLogger.sendAlarm ("MsoDatabaseAccessError",
799                                    MsoAlarmLogger.CRITICAL,
800                                    Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
801             msoRequest.createRequestRecord (Status.FAILED);
802             msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with DB");
803             msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
804             return response;
805         }
806     }
807 }