79ac76ff041e020a8d7c78b04b21ff169786df40
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / MsoRequest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.mso.apihandlerinfra;
23
24 import org.codehaus.jackson.JsonGenerationException;
25 import org.codehaus.jackson.map.JsonMappingException;
26 import org.codehaus.jackson.map.ObjectMapper;
27 import org.codehaus.jackson.map.annotate.JsonSerialize;
28 import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
29 import org.hibernate.Session;
30 import org.openecomp.mso.apihandler.common.ValidationException;
31 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.CloudConfiguration;
32 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ModelInfo;
33 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.PolicyException;
34 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RelatedInstance;
35 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RelatedInstanceList;
36 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestError;
37 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestInfo;
38 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestParameters;
39 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ServiceException;
40 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ServiceInstancesRequest;
41 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.SubscriberInfo;
42 import org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType;
43 import org.openecomp.mso.apihandlerinfra.vnfbeans.VnfInputs;
44 import org.openecomp.mso.apihandlerinfra.vnfbeans.VnfRequest;
45 import org.openecomp.mso.db.AbstractSessionFactoryManager;
46 import org.openecomp.mso.logger.MessageEnum;
47 import org.openecomp.mso.logger.MsoLogger;
48 import org.openecomp.mso.requestsdb.InfraActiveRequests;
49 import org.openecomp.mso.requestsdb.RequestsDatabase;
50 import org.openecomp.mso.requestsdb.RequestsDbSessionFactoryManager;
51 import org.openecomp.mso.utils.UUIDChecker;
52 import org.w3c.dom.Document;
53 import org.w3c.dom.Element;
54 import org.w3c.dom.Node;
55 import org.w3c.dom.NodeList;
56
57 import javax.ws.rs.core.MultivaluedMap;
58 import javax.ws.rs.core.Response;
59 import javax.xml.bind.JAXBContext;
60 import javax.xml.bind.JAXBException;
61 import javax.xml.bind.Marshaller;
62 import javax.xml.transform.OutputKeys;
63 import javax.xml.transform.Transformer;
64 import javax.xml.transform.TransformerFactory;
65 import javax.xml.transform.dom.DOMSource;
66 import javax.xml.transform.stream.StreamResult;
67 import java.io.IOException;
68 import java.io.StringWriter;
69 import java.sql.Timestamp;
70 import java.util.ArrayList;
71 import java.util.HashMap;
72 import java.util.List;
73 import java.util.Map;
74 import java.util.Map.Entry;
75 import java.util.StringTokenizer;
76
77 public class MsoRequest {
78
79     private String requestId;
80     private String requestXML;
81     private String requestJSON;
82     private String requestUri;
83     private VnfRequest vnfReq;
84     private RequestInfo requestInfo;
85     private ModelInfo modelInfo;
86     private CloudConfiguration cloudConfiguration ;
87     private VnfInputs vnfInputs;
88     private String vnfParams;
89     private Action action;
90     private String errorMessage;
91     private String errorCode;
92     private String httpResponse;
93     private String responseBody;
94     private RequestStatusType status;
95     private ServiceInstancesRequest sir;
96     private long startTime;
97     private long progress = Constants.PROGRESS_REQUEST_RECEIVED;
98     private String serviceInstanceType;
99     private String vnfType;
100     private String vfModuleType;
101     private String vfModuleModelName;
102     private String networkType;
103     private String asdcServiceModelVersion;
104     private String requestScope;
105     private int reqVersion;
106     private boolean aLaCarteFlag = false;
107
108     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
109     private static final String NOT_PROVIDED = "not provided";
110
111     protected AbstractSessionFactoryManager requestsDbSessionFactoryManager = new RequestsDbSessionFactoryManager ();
112
113     MsoRequest (String requestId) {
114         this.requestId = requestId;
115         this.startTime = System.currentTimeMillis();
116         MsoLogger.setLogContext (requestId, null);
117
118     }
119
120     MsoRequest () {
121
122         this.startTime = System.currentTimeMillis();
123         MsoLogger.setLogContext (requestId, null);
124
125     }
126
127
128     public Response buildServiceErrorResponse (int httpResponseCode,
129             MsoException exceptionType,
130             String text,
131             String messageId,
132             List<String> variables) {
133
134         this.errorCode = messageId;
135
136         if (text != null) {
137                 this.errorMessage = text;
138         }
139         else {
140                 this.errorMessage = "";
141         }
142         this.httpResponse = Integer.toString(httpResponseCode);
143         if(errorMessage.length() > 1999){
144             errorMessage = errorMessage.substring(0, 1999);
145         }
146
147         RequestError re = new RequestError();
148
149         if("PolicyException".equals(exceptionType.name())){
150
151                 PolicyException pe = new PolicyException();
152                 pe.setMessageId(messageId);
153                 pe.setText(text);
154                 if(variables != null){
155                         for(String variable: variables){
156                                 pe.getVariables().add(variable);
157                         }
158                 }
159                 re.setPolicyException(pe);
160
161         } else {
162
163                 ServiceException se = new ServiceException();
164                 se.setMessageId(messageId);
165                 se.setText(text);
166                 if(variables != null){
167                                 for(String variable: variables){
168                                         se.getVariables().add(variable);
169                                 }
170                 }
171                 re.setServiceException(se);
172         }
173
174         String requestErrorStr = null;
175
176         try{
177                 ObjectMapper mapper = new ObjectMapper();
178                 mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
179                 requestErrorStr = mapper.writeValueAsString(re);
180         }catch(Exception e){
181                 msoLogger.error (MessageEnum.APIH_VALIDATION_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception in buildServiceErrorResponse writing exceptionType to string ", e);
182         }
183
184
185         return Response.status (httpResponseCode).entity(requestErrorStr).build ();
186
187     }
188
189     private int reqVersionToInt(String version){
190         if(version!=null){
191                 return Integer.parseInt(version.substring(1));
192         }else{
193                 return 0;
194         }
195     }
196
197     // Parse request JSON
198     void parse (ServiceInstancesRequest sir, HashMap<String,String> instanceIdMap, Action action, String version) throws ValidationException {
199
200         msoLogger.debug ("Validating the Service Instance request");
201
202         this.sir = sir;
203         this.action = action;
204         this.reqVersion = reqVersionToInt(version);
205         msoLogger.debug ("Incoming version is: " + version + " coverting to int: " + this.reqVersion);
206
207
208         try{
209                 ObjectMapper mapper = new ObjectMapper();
210                 //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
211                 requestJSON = mapper.writeValueAsString(sir.getRequestDetails());
212
213         } catch(Exception e){
214                 throw new ValidationException ("Parse ServiceInstanceRequest to JSON string",e);
215         }
216
217         if(instanceIdMap != null){
218                 if(instanceIdMap.get("serviceInstanceId") != null){
219                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("serviceInstanceId"))) {
220                                 throw new ValidationException ("serviceInstanceId");
221                         }
222                         this.sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
223                 }
224
225                 if(instanceIdMap.get("vnfInstanceId") != null){
226                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("vnfInstanceId"))) {
227                                 throw new ValidationException ("vnfInstanceId");
228                         }
229                         this.sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId"));
230                 }
231
232                 if(instanceIdMap.get("vfModuleInstanceId") != null){
233                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("vfModuleInstanceId"))) {
234                                 throw new ValidationException ("vfModuleInstanceId");
235                         }
236                         this.sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId"));
237                 }
238
239                 if(instanceIdMap.get("volumeGroupInstanceId") != null){
240                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("volumeGroupInstanceId"))) {
241                                 throw new ValidationException ("volumeGroupInstanceId");
242                         }
243                         this.sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId"));
244                 }
245
246                 if(instanceIdMap.get("networkInstanceId") != null){
247                         if (!UUIDChecker.isValidUUID (instanceIdMap.get ("networkInstanceId"))) {
248                                 throw new ValidationException ("networkInstanceId");
249                         }
250                         this.sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId"));
251                 }
252         }
253
254         RequestParameters requestParameters = sir.getRequestDetails().getRequestParameters();
255                 if (this.reqVersion >= 3) {
256                         this.aLaCarteFlag =
257                                 requestParameters != null && sir.getRequestDetails().getRequestParameters().isaLaCarte();
258                 } else {
259                         this.aLaCarteFlag = true;
260                 }
261
262                 if(requestParameters != null && (reqVersion < 3) && requestParameters.getAutoBuildVfModules()){
263                 throw new ValidationException("AutoBuildVfModule", version);
264         }
265
266         this.modelInfo = sir.getRequestDetails().getModelInfo();
267
268         if (this.modelInfo == null) {
269             throw new ValidationException ("model-info");
270         }
271
272         this.requestInfo = sir.getRequestDetails().getRequestInfo();
273
274         if (this.requestInfo == null) {
275             throw new ValidationException ("requestInfo");
276         }
277
278         if (modelInfo.getModelType () == null) {
279                 throw new ValidationException ("modelType");
280         }
281
282         this.requestScope = modelInfo.getModelType().name();
283
284         // modelCustomizationId is required when usePreLoad is false for v4 and higher for VF Module Create
285         if(requestParameters != null && reqVersion > 3 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.createInstance && !requestParameters.isUsePreload()) {
286                 if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) {
287                         throw new ValidationException("modelCustomizationId");
288                 }
289         }
290         
291         // modelCustomizationId is required when usePreLoad is false for v5 and higher for VF Module Replace
292         if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.replaceInstance && !requestParameters.isUsePreload()) {
293                 if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) {
294                         throw new ValidationException("modelCustomizationId");
295                 }
296         }
297         
298         // modelCustomizationId or modelCustomizationName are required when usePreLoad is false for v5 and higher for VNF Replace
299         if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.replaceInstance && !requestParameters.isUsePreload()) {
300                 if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId()) && modelInfo.getModelCustomizationName() == null) {
301                         throw new ValidationException("modelCustomizationId or modelCustomizationName");
302                 }
303         }
304
305         //is required for serviceInstance delete macro when aLaCarte=false (v3)
306         //create and updates except for network (except v4)
307         if (empty (modelInfo.getModelInvariantId ()) && ((this.reqVersion >2 && !this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) ||
308                 !(this.reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) && (action == Action.createInstance || action == Action.updateInstance))) {
309                 throw new ValidationException ("modelInvariantId");
310         }
311
312         if (!empty (modelInfo.getModelInvariantId ()) && !UUIDChecker.isValidUUID (modelInfo.getModelInvariantId ())) {
313                 throw new ValidationException ("modelInvariantId format");
314         }
315
316         if (this.reqVersion <= 2 && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance || (action == Action.deleteInstance &&
317                         (requestScope.equalsIgnoreCase (ModelType.network.name ()) || requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))) {
318                 throw new ValidationException ("modelName");
319         }
320         if(this.reqVersion > 2 && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance || (action == Action.deleteInstance &&
321                         (requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))){
322                 throw new ValidationException ("modelName");
323         }
324
325         if (empty (modelInfo.getModelVersion ()) && ((this.reqVersion == 3 && !this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) || 
326                         !(this.reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) && (action == Action.createInstance || action == Action.updateInstance))) {
327                 throw new ValidationException ("modelVersion");
328         }
329
330         // modelVersionId doesn't exist in v2, not required field in v3, is required for serviceInstance delete macro when aLaCarte=false in v4
331         if (this.reqVersion > 3 && empty (modelInfo.getModelVersionId()) && ((!this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) ||
332                         (action == Action.createInstance || action == Action.updateInstance))) {
333                 throw new ValidationException ("modelVersionId");
334         }
335         
336         if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action != Action.deleteInstance && empty (modelInfo.getModelCustomizationName ())) {
337                 if(this.reqVersion<=2){
338                         throw new ValidationException ("modelCustomizationName");
339                 } else if (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) {
340                         throw new ValidationException ("modelCustomizationId or modelCustomizationName");
341                 }
342         }
343
344         if(this.reqVersion > 2 && (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) && requestScope.equalsIgnoreCase (ModelType.network.name ())
345                         && (action == Action.updateInstance || action == Action.createInstance)){
346                 throw new ValidationException ("modelCustomizationId");
347         }
348
349         if(!empty(modelInfo.getModelNameVersionId())){
350                 modelInfo.setModelVersionId(modelInfo.getModelNameVersionId());
351         }
352
353         this.cloudConfiguration = sir.getRequestDetails ().getCloudConfiguration ();
354         if ( (((!this.aLaCarteFlag && requestScope.equalsIgnoreCase (ModelType.service.name ()) && this.reqVersion < 5) ||
355                         (!requestScope.equalsIgnoreCase (ModelType.service.name ())) && action != Action.updateInstance))
356                         && cloudConfiguration == null) {
357                 throw new ValidationException ("cloudConfiguration");
358         }
359
360         if (cloudConfiguration != null) {
361                 if (empty (cloudConfiguration.getLcpCloudRegionId ())) {
362                         throw new ValidationException ("lcpCloudRegionId");
363                 }
364                 if (empty (cloudConfiguration.getTenantId ())) {
365                         throw new ValidationException ("tenantId");
366                 }
367         }
368
369
370         if (requestScope.equalsIgnoreCase (ModelType.service.name ()) && action == Action.createInstance) {
371                 if (requestParameters == null) {
372                         throw new ValidationException ("requestParameters");
373                 }
374                 if (empty (requestParameters.getSubscriptionServiceType ())) {
375                         throw new ValidationException ("subscriptionServiceType");
376                 }
377         }
378         
379         if (this.reqVersion > 4 && requestScope.equalsIgnoreCase (ModelType.service.name ()) && action == Action.createInstance) {
380                 SubscriberInfo subscriberInfo = sir.getRequestDetails ().getSubscriberInfo();
381                 if (subscriberInfo == null) {
382                         throw new ValidationException ("subscriberInfo");
383                 }
384                 if (empty (subscriberInfo.getGlobalSubscriberId ())) {
385                         throw new ValidationException ("globalSubscriberId");
386                 }
387         }
388
389         if(requestScope.equalsIgnoreCase(ModelType.service.name())){
390                 this.serviceInstanceType = modelInfo.getModelName();
391         }
392
393         if(requestScope.equalsIgnoreCase(ModelType.network.name())){
394                 this.networkType = modelInfo.getModelName();
395         }
396
397         // Verify instanceName existence and format except for macro serviceInstance
398         if (this.reqVersion < 3 && requestScope.equalsIgnoreCase (ModelType.service.name ()) && empty (requestInfo.getInstanceName ()) && action == Action.createInstance) {
399                 throw new ValidationException ("instanceName");
400         }
401
402         if (!empty (requestInfo.getInstanceName ())) {
403                 if (!requestInfo.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) {
404                         throw new ValidationException ("instanceName format");
405                 }
406         }
407
408         if (empty (requestInfo.getProductFamilyId ()))  {
409                 // Mandatory for vnf Create(aLaCarte=true), Network Create(aLaCarte=true) and network update
410                 //Mandatory for macro request create service instance
411                 if((requestScope.equalsIgnoreCase (ModelType.vnf.name ()) && action == Action.createInstance) || 
412                         (requestScope.equalsIgnoreCase (ModelType.network.name ()) && (action == Action.createInstance || action == Action.updateInstance)) ||
413                         (this.reqVersion > 3 && !this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.createInstance)) {
414                 throw new ValidationException ("productFamilyId");
415         }
416         }
417        
418         //required for all operations in V4
419         if(empty(requestInfo.getRequestorId()) && this.reqVersion > 3) {
420                 throw new ValidationException ("requestorId");
421         }
422
423         if (empty (requestInfo.getSource ())) {
424                 throw new ValidationException ("source");
425         }
426
427
428         RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
429
430         String serviceModelName = null;
431         String vnfModelName = null;
432         String asdcServiceModelVersion = null;
433         String volumeGroupId = null;
434         boolean isRelatedServiceInstancePresent = false;
435         boolean isRelatedVnfInstancePresent = false;
436
437         if (instanceList != null) {
438                 for(RelatedInstanceList relatedInstanceList : instanceList){
439                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
440
441                         ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo ();
442                                 if (relatedInstanceModelInfo == null) {
443                                 throw new ValidationException ("modelInfo in relatedInstance");
444                         }
445
446                         if (relatedInstanceModelInfo.getModelType () == null) {
447                                 throw new ValidationException ("modelType in relatedInstance");
448                         }
449
450
451                         if (!empty (relatedInstance.getInstanceName ())) {
452                         if (!relatedInstance.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) {
453                                 throw new ValidationException ("instanceName format in relatedInstance");
454                         }
455                     }
456
457                         if (empty (relatedInstance.getInstanceId ())) {
458                                 throw new ValidationException ("instanceId in relatedInstance");
459                         }
460
461                         if (!UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) {
462                                 throw new ValidationException ("instanceId format in relatedInstance");
463                         }
464
465
466                         if (action != Action.deleteInstance) {
467                                 if(!relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {
468
469                                         if(empty (relatedInstanceModelInfo.getModelInvariantId ())) {
470                                         throw new ValidationException ("modelInvariantId in relatedInstance");
471                                         } else if(this.reqVersion > 3 && empty(relatedInstanceModelInfo.getModelVersionId ())) {
472                                                 throw new ValidationException("modelVersionId in relatedInstance");
473                                         } else if(empty(relatedInstanceModelInfo.getModelName ())) {
474                                                 throw new ValidationException ("modelName in relatedInstance");
475                                         } else if (empty (relatedInstanceModelInfo.getModelVersion ())) {
476                                                 throw new ValidationException ("modelVersion in relatedInstance");
477                                         }
478                                 }
479
480                                 if (!empty (relatedInstanceModelInfo.getModelInvariantId ()) &&
481                                                 !UUIDChecker.isValidUUID (relatedInstanceModelInfo.getModelInvariantId ())) {
482                                         throw new ValidationException ("modelInvariantId format in relatedInstance");
483                                 }
484                                 }
485
486                         if (empty (relatedInstanceModelInfo.getModelCustomizationName ()) && relatedInstanceModelInfo.getModelType ().equals (ModelType.vnf) ) {
487                                 if(this.reqVersion >=3 && empty (relatedInstanceModelInfo.getModelCustomizationId()) && action != Action.deleteInstance) {
488                                         throw new ValidationException ("modelCustomizationName or modelCustomizationId in relatedInstance of vnf");
489                                 } else if(this.reqVersion < 3) {
490                                         throw new ValidationException ("modelCustomizationName in relatedInstance");
491                         }
492                         }
493
494                         if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
495                                 isRelatedServiceInstancePresent = true;
496                                 if (!relatedInstance.getInstanceId ().equals (this.sir.getServiceInstanceId ())) {
497                                         throw new ValidationException ("serviceInstanceId matching the serviceInstanceId in request URI");
498                                 }
499                                 serviceModelName = relatedInstanceModelInfo.getModelName ();
500                                 asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion ();
501                         } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
502                                 isRelatedVnfInstancePresent = true;
503                                 if (!relatedInstance.getInstanceId ().equals (this.sir.getVnfInstanceId ())) {
504                                         throw new ValidationException ("vnfInstanceId matching the vnfInstanceId in request URI");
505                                 }
506                                 vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
507                         } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {                              
508                                 volumeGroupId = relatedInstance.getInstanceId ();
509                         }
510                 }
511
512
513                 if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) {
514                         if (!isRelatedServiceInstancePresent) {
515                                 throw new ValidationException ("related service instance for volumeGroup request");
516                         }
517                         if (!isRelatedVnfInstancePresent) {
518                                 throw new ValidationException ("related vnf instance for volumeGroup request");
519                         }
520                         this.serviceInstanceType = serviceModelName;
521                         this.vnfType = serviceModelName + "/" + vnfModelName;
522                         this.asdcServiceModelVersion = asdcServiceModelVersion;
523                 }
524                 else if(requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) {
525                         if (!isRelatedServiceInstancePresent) {
526                                 throw new ValidationException ("related service instance for vfModule request");
527                         }
528                         if (!isRelatedVnfInstancePresent) {
529                                 throw new ValidationException ("related vnf instance for vfModule request");
530                         }
531                         String vfModuleModelName = modelInfo.getModelName ();
532                         this.vfModuleModelName = vfModuleModelName;
533                         this.serviceInstanceType = serviceModelName;
534                         this.vnfType = serviceModelName + "/" + vnfModelName;
535                         this.asdcServiceModelVersion = asdcServiceModelVersion;
536                         this.vfModuleType = vnfType + "::" + vfModuleModelName;
537                         this.sir.setVolumeGroupInstanceId (volumeGroupId);
538                 }
539                 else if (requestScope.equalsIgnoreCase (ModelType.vnf.name ())) {
540                         if (!isRelatedServiceInstancePresent) {
541                                 throw new ValidationException ("related service instance for vnf request");
542                         }
543                         this.vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();
544                }
545         }
546         else if ((( requestScope.equalsIgnoreCase(ModelType.vnf.name ()) || requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ()) ) && (action == Action.createInstance)) ||
547                         (this.reqVersion > 2 && (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) && action == Action.updateInstance)){
548                  msoLogger.debug ("related instance exception");
549                 throw new ValidationException ("related instances");
550         }
551
552     }
553
554     void parseOrchestration (ServiceInstancesRequest sir) throws ValidationException {
555
556         msoLogger.debug ("Validating the Orchestration request");
557
558         this.sir = sir;
559
560         try{
561                 ObjectMapper mapper = new ObjectMapper();
562                 //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
563                 requestJSON = mapper.writeValueAsString(sir.getRequestDetails());
564
565         } catch(Exception e){
566                 throw new ValidationException ("Parse ServiceInstanceRequest to JSON string", e);
567         }
568
569         this.requestInfo = sir.getRequestDetails().getRequestInfo();
570
571         if (this.requestInfo == null) {
572             throw new ValidationException ("requestInfo");
573         }
574
575         if (empty (requestInfo.getSource ())) {
576                 throw new ValidationException ("source");
577         }
578         if (empty (requestInfo.getRequestorId ())) {
579                 throw new ValidationException ("requestorId");
580         }
581     }
582
583     public Map<String, List<String>> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException {
584
585         String queryParam = null;
586         Map<String, List<String>> orchestrationFilterParams = new HashMap<>();
587
588
589         for (Entry<String,List<String>> entry : queryParams.entrySet()) {
590             queryParam = entry.getKey();
591
592             try{
593                   if("filter".equalsIgnoreCase(queryParam)){
594                           for(String value : entry.getValue()) {
595                                   StringTokenizer st = new StringTokenizer(value, ":");
596         
597                                   int counter=0;
598                                   String mapKey=null;
599                                   List<String> orchestrationList = new ArrayList<>();
600                                   while (st.hasMoreElements()) {
601                                           if(counter == 0){
602                                                   mapKey = st.nextElement() + "";
603                                           } else{
604                                                   orchestrationList.add(st.nextElement() + "");
605                                           }
606                                          counter++;
607                                   }
608                                   orchestrationFilterParams.put(mapKey, orchestrationList);
609                           }
610                   }
611
612             }catch(Exception e){
613                 //msoLogger.error (MessageEnum.APIH_VALIDATION_ERROR, e);
614                 throw new ValidationException ("QueryParam ServiceInfo", e);
615
616                 }
617
618         }
619
620
621         return orchestrationFilterParams;
622   }
623
624     public void createRequestRecord (Status status, Action action) {
625
626         Session session = null;
627         try {
628
629             session = requestsDbSessionFactoryManager.getSessionFactory ().openSession ();
630             session.beginTransaction ();
631
632             if (null == sir) {
633                 sir = new ServiceInstancesRequest ();
634             }
635
636             InfraActiveRequests aq = new InfraActiveRequests ();
637             aq.setRequestId (requestId);
638
639             aq.setRequestAction(action.name());
640             aq.setAction(action.name());
641
642             Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
643
644             aq.setStartTime (startTimeStamp);
645
646             if (requestInfo != null) {
647
648                 if(requestInfo.getSource() != null){
649                         aq.setSource(requestInfo.getSource());
650                 }
651                 if(requestInfo.getCallbackUrl() != null){
652                         aq.setCallBackUrl(requestInfo.getCallbackUrl());
653                 }
654                 if(requestInfo.getCorrelator() != null){
655                         aq.setCorrelator(requestInfo.getCorrelator());
656                 }
657
658                 if(requestInfo.getRequestorId() != null) {
659                         aq.setRequestorId(requestInfo.getRequestorId());
660                 }
661             }
662
663             if (modelInfo != null) {
664                 aq.setRequestScope(requestScope);
665             }
666
667             if (cloudConfiguration != null) {
668                 if(cloudConfiguration.getLcpCloudRegionId() != null) {
669                         aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId());
670                 }
671
672                 if(cloudConfiguration.getTenantId() != null) {
673                         aq.setTenantId(cloudConfiguration.getTenantId());
674                 }
675
676             }
677
678             if(sir.getServiceInstanceId() != null){
679                 aq.setServiceInstanceId(sir.getServiceInstanceId());
680             }
681
682             if(sir.getVnfInstanceId() != null){
683                 aq.setVnfId(sir.getVnfInstanceId());
684             }
685
686
687             if(ModelType.service.name().equalsIgnoreCase(requestScope)){
688                 if(requestInfo.getInstanceName() != null){
689                         aq.setServiceInstanceName(requestInfo.getInstanceName());
690                 }
691             }
692
693             if(ModelType.network.name().equalsIgnoreCase(requestScope)){
694                 aq.setNetworkName(requestInfo.getInstanceName());
695                 aq.setNetworkType(networkType);
696                 aq.setNetworkId(sir.getNetworkInstanceId());
697             }
698
699             if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)){
700                 aq.setVolumeGroupId(sir.getVolumeGroupInstanceId());
701                 aq.setVolumeGroupName(requestInfo.getInstanceName());
702                 aq.setVnfType(vnfType);
703
704             }
705
706             if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)){
707                 aq.setVfModuleName(requestInfo.getInstanceName());
708                 aq.setVfModuleModelName(modelInfo.getModelName());
709                 aq.setVfModuleId(sir.getVfModuleInstanceId());
710                 aq.setVolumeGroupId(sir.getVolumeGroupInstanceId());
711                 aq.setVnfType(vnfType);
712
713             }
714
715             if(ModelType.vnf.name().equalsIgnoreCase(requestScope)){
716                 aq.setVnfName(requestInfo.getInstanceName());
717                                 if (null != sir.getRequestDetails()) {
718                                         RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
719
720                                         if (instanceList != null) {
721
722                                                 for(RelatedInstanceList relatedInstanceList : instanceList){
723
724                                                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
725                                                         if(relatedInstance.getModelInfo().getModelType().equals(ModelType.service)){
726                                                                 aq.setVnfType(vnfType);
727                                                         }
728                                                 }
729                                         }
730                                 }
731             }
732
733             aq.setRequestBody (this.requestJSON);
734
735             aq.setRequestStatus (status.toString ());
736             aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
737
738             if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
739                 aq.setStatusMessage (this.errorMessage);
740                 aq.setResponseBody (this.responseBody);
741                 aq.setProgress(100L);
742
743                 Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis());
744                 aq.setEndTime (endTimeStamp);
745             }
746
747             msoLogger.debug ("About to insert a record");
748
749             session.save (aq);
750             session.getTransaction ().commit ();
751             session.close ();
752         } catch (Exception e) {
753                 msoLogger.error (MessageEnum.APIH_DB_INSERT_EXC, "", "", MsoLogger.ErrorCode.DataError, "Exception when creation record request", e);
754             if (session != null) {
755                 session.close ();
756             }
757             if (!status.equals (Status.FAILED)) {
758                 throw e;
759             }
760         }
761     }
762
763     public void updateFinalStatus (Status status) {
764         int result = 0;
765         try {
766             result = (RequestsDatabase.getInstance()).updateInfraFinalStatus (requestId,
767                                                               status.toString (),
768                                                               this.errorMessage,
769                                                               this.progress,
770                                                               this.responseBody,
771                                                               Constants.MODIFIED_BY_APIHANDLER);
772         } catch (Exception e) {
773                 msoLogger.error(MessageEnum.APIH_DB_UPDATE_EXC, e.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "Exception when updating record in DB");
774             msoLogger.debug ("Exception: ", e);
775         }
776     }
777
778     public Response buildResponse (int httpResponseCode, String errorCode, InfraActiveRequests inProgress) {
779         return buildResponseWithError (httpResponseCode, errorCode, inProgress, null);
780     }
781
782     public Response buildResponseWithError (int httpResponseCode,
783                                             String errorCode,
784                                             InfraActiveRequests inProgress,
785                                             String errorString) {
786
787
788
789         // Log the failed request into the MSO Requests database
790
791         return Response.status (httpResponseCode).entity (null).build ();
792
793     }
794
795     public Response buildResponseFailedValidation (int httpResponseCode, String exceptionMessage) {
796
797
798
799         return Response.status (httpResponseCode).entity (null).build ();
800     }
801
802     public String getRequestUri () {
803         return requestUri;
804     }
805
806     public void setRequestUri (String requestUri) {
807         this.requestUri = requestUri;
808     }
809
810     public VnfInputs getVnfInputs () {
811         return vnfInputs;
812     }
813
814     public RequestInfo getRequestInfo () {
815         return requestInfo;
816     }
817
818     public String getResponseBody () {
819         return responseBody;
820     }
821
822     public void setResponseBody (String responseBody) {
823         this.responseBody = responseBody;
824     }
825
826     public String getHttpResponse () {
827         return httpResponse;
828     }
829
830     public void setHttpResponse (String httpResponse) {
831         this.httpResponse = httpResponse;
832     }
833
834     public String getRequestId () {
835         return requestId;
836     }
837
838     public String getRequestXML () {
839         return requestXML;
840     }
841
842     public void setRequestXML (String requestXML) {
843         this.requestXML = requestXML;
844     }
845
846     public RequestStatusType getStatus () {
847         return status;
848     }
849
850     public String getServiceType () {
851         if (this.vnfInputs.getServiceType () != null)
852                 return this.vnfInputs.getServiceType ();
853         if (this.vnfInputs.getServiceId () != null)
854                 return this.vnfInputs.getServiceId ();
855         return null;
856     }
857
858     public void setStatus (RequestStatusType status) {
859         this.status = status;
860         switch (status) {
861         case FAILED:
862         case COMPLETE:
863                 this.progress = Constants.PROGRESS_REQUEST_COMPLETED;
864                 break;
865         case IN_PROGRESS:
866                 this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS;
867                 break;
868         }
869     }
870
871     public ModelInfo getModelInfo() {
872         return modelInfo;
873     }
874
875     public ServiceInstancesRequest getServiceInstancesRequest() {
876         return sir;
877     }
878
879     public String getServiceInstanceType () {
880         return serviceInstanceType;
881     }
882
883     public String getNetworkType () {
884         return networkType;
885     }
886
887     public String getVnfType () {
888         return vnfType;
889     }
890
891     public String getVfModuleModelName () {
892         return vfModuleModelName;
893     }
894
895     public String getVfModuleType () {
896         return vfModuleType;
897     }
898
899     public String getAsdcServiceModelVersion () {
900         return asdcServiceModelVersion;
901     }
902
903     public static String domToStr (Document doc) {
904         if (doc == null) {
905             return null;
906         }
907
908         try {
909             StringWriter sw = new StringWriter ();
910             StreamResult sr = new StreamResult (sw);
911             TransformerFactory tf = TransformerFactory.newInstance ();
912             Transformer t = tf.newTransformer ();
913             t.setOutputProperty (OutputKeys.STANDALONE, "yes");
914             NodeList nl = doc.getDocumentElement ().getChildNodes ();
915             DOMSource source = null;
916             for (int x = 0; x < nl.getLength (); x++) {
917                 Node e = nl.item (x);
918                 if (e instanceof Element) {
919                     source = new DOMSource (e);
920                     break;
921                 }
922             }
923             if (source != null) {
924                 t.transform (source, sr);
925
926                 String s = sw.toString ();
927                 return s;
928             }
929
930             return null;
931
932         } catch (Exception e) {
933             msoLogger.error (MessageEnum.APIH_DOM2STR_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception in domToStr", e);
934         }
935         return null;
936     }
937
938     public void addBPMNSpecificInputs(String personaModelId, String personaModelVersion, Boolean isBaseVfModule,
939                         String vnfPersonaModelId, String vnfPersonaModelVersion) {
940         vnfInputs.setPersonaModelId(personaModelId);
941         vnfInputs.setPersonaModelVersion(personaModelVersion);
942         vnfInputs.setIsBaseVfModule(isBaseVfModule);
943         vnfInputs.setVnfPersonaModelId(vnfPersonaModelId);
944         vnfInputs.setVnfPersonaModelVersion(vnfPersonaModelVersion);
945
946         this.vnfReq.setVnfInputs(vnfInputs);
947
948           StringWriter stringWriter = new StringWriter ();
949           try {
950               JAXBContext jaxbContext = JAXBContext.newInstance (VnfRequest.class);
951               Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
952
953               // output pretty printed
954               jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
955
956               jaxbMarshaller.marshal (this.vnfReq, stringWriter);
957
958           } catch (JAXBException e) {
959               msoLogger.debug ("Exception: ", e);
960           }
961
962           this.requestXML = stringWriter.toString ();
963           msoLogger.debug("REQUEST XML to BPEL: " + this.requestXML);
964
965
966     }
967
968     private static boolean empty(String s) {
969           return (s == null || s.trim().isEmpty());
970     }
971
972     public String getRequestJSON() throws JsonGenerationException, JsonMappingException, IOException {
973         ObjectMapper mapper = new ObjectMapper();
974         mapper.setSerializationInclusion(Inclusion.NON_NULL);
975         //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
976         msoLogger.debug ("building sir from object " + sir);
977         requestJSON = mapper.writeValueAsString(sir);
978         
979         // Perform mapping from VID-style modelInfo fields to ASDC-style modelInfo fields
980         
981         msoLogger.debug("REQUEST JSON before mapping: " + requestJSON);
982         // modelUuid = modelVersionId
983         requestJSON = requestJSON.replaceAll("\"modelVersionId\":","\"modelUuid\":");
984         // modelCustomizationUuid = modelCustomizationId
985         requestJSON = requestJSON.replaceAll("\"modelCustomizationId\":","\"modelCustomizationUuid\":");
986         // modelInstanceName = modelCustomizationName
987         requestJSON = requestJSON.replaceAll("\"modelCustomizationName\":","\"modelInstanceName\":");
988         // modelInvariantUuid = modelInvariantId 
989         requestJSON = requestJSON.replaceAll("\"modelInvariantId\":","\"modelInvariantUuid\":");        
990         msoLogger.debug("REQUEST JSON after mapping: " + requestJSON);
991         
992         return requestJSON;
993     }
994
995         public boolean getALaCarteFlag() {
996                 return aLaCarteFlag;
997         }
998
999         public void setaLaCarteFlag(boolean aLaCarteFlag) {
1000                 this.aLaCarteFlag = aLaCarteFlag;
1001         }
1002
1003         public int getReqVersion() {
1004                 return reqVersion;
1005         }
1006
1007         public void setReqVersion(int reqVersion) {
1008                 this.reqVersion = reqVersion;
1009         }
1010 }