Fix major sonar issues
[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                 if(requestParameters!=null){
257                         this.aLaCarteFlag = sir.getRequestDetails().getRequestParameters().getALaCarte();
258                 }else{
259                         this.aLaCarteFlag = false;
260                 }
261         }else{
262                 this.aLaCarteFlag = true;
263         }
264
265                 if(requestParameters != null && (reqVersion < 3) && requestParameters.getAutoBuildVfModules()){
266                 throw new ValidationException("AutoBuildVfModule", version);
267         }
268
269         this.modelInfo = sir.getRequestDetails().getModelInfo();
270
271         if (this.modelInfo == null) {
272             throw new ValidationException ("model-info");
273         }
274
275         this.requestInfo = sir.getRequestDetails().getRequestInfo();
276
277         if (this.requestInfo == null) {
278             throw new ValidationException ("requestInfo");
279         }
280
281         if (modelInfo.getModelType () == null) {
282                 throw new ValidationException ("modelType");
283         }
284
285         this.requestScope = modelInfo.getModelType().name();
286
287         // modelCustomizationId is required when usePreLoad is false for v4 and higher for VF Module Create
288         if(requestParameters != null && reqVersion > 3 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.createInstance && !requestParameters.isUsePreload()) {
289                 if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) {
290                         throw new ValidationException("modelCustomizationId");
291                 }
292         }
293         
294         // modelCustomizationId is required when usePreLoad is false for v5 and higher for VF Module Replace
295         if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.replaceInstance && !requestParameters.isUsePreload()) {
296                 if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) {
297                         throw new ValidationException("modelCustomizationId");
298                 }
299         }
300         
301         // modelCustomizationId or modelCustomizationName are required when usePreLoad is false for v5 and higher for VNF Replace
302         if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.replaceInstance && !requestParameters.isUsePreload()) {
303                 if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId()) && modelInfo.getModelCustomizationName() == null) {
304                         throw new ValidationException("modelCustomizationId or modelCustomizationName");
305                 }
306         }
307
308         //is required for serviceInstance delete macro when aLaCarte=false (v3)
309         //create and updates except for network (except v4)
310         if (empty (modelInfo.getModelInvariantId ()) && ((this.reqVersion >2 && !this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) ||
311                 !(this.reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) && (action == Action.createInstance || action == Action.updateInstance))) {
312                 throw new ValidationException ("modelInvariantId");
313         }
314
315         if (!empty (modelInfo.getModelInvariantId ()) && !UUIDChecker.isValidUUID (modelInfo.getModelInvariantId ())) {
316                 throw new ValidationException ("modelInvariantId format");
317         }
318
319         if (this.reqVersion <= 2 && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance || (action == Action.deleteInstance &&
320                         (requestScope.equalsIgnoreCase (ModelType.network.name ()) || requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))) {
321                 throw new ValidationException ("modelName");
322         }
323         if(this.reqVersion > 2 && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance || (action == Action.deleteInstance &&
324                         (requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))){
325                 throw new ValidationException ("modelName");
326         }
327
328         if (empty (modelInfo.getModelVersion ()) && ((this.reqVersion == 3 && !this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) || 
329                         !(this.reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) && (action == Action.createInstance || action == Action.updateInstance))) {
330                 throw new ValidationException ("modelVersion");
331         }
332
333         // modelVersionId doesn't exist in v2, not required field in v3, is required for serviceInstance delete macro when aLaCarte=false in v4
334         if (this.reqVersion > 3 && empty (modelInfo.getModelVersionId()) && ((!this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) ||
335                         (action == Action.createInstance || action == Action.updateInstance))) {
336                 throw new ValidationException ("modelVersionId");
337         }
338         
339         if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action != Action.deleteInstance && empty (modelInfo.getModelCustomizationName ())) {
340                 if(this.reqVersion<=2){
341                         throw new ValidationException ("modelCustomizationName");
342                 } else if (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) {
343                         throw new ValidationException ("modelCustomizationId or modelCustomizationName");
344                 }
345         }
346
347         if(this.reqVersion > 2 && (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) && requestScope.equalsIgnoreCase (ModelType.network.name ())
348                         && (action == Action.updateInstance || action == Action.createInstance)){
349                 throw new ValidationException ("modelCustomizationId");
350         }
351
352         if(!empty(modelInfo.getModelNameVersionId())){
353                 modelInfo.setModelVersionId(modelInfo.getModelNameVersionId());
354         }
355
356         this.cloudConfiguration = sir.getRequestDetails ().getCloudConfiguration ();
357         if ( (((!this.aLaCarteFlag && requestScope.equalsIgnoreCase (ModelType.service.name ()) && this.reqVersion < 5) ||
358                         (!requestScope.equalsIgnoreCase (ModelType.service.name ())) && action != Action.updateInstance))
359                         && cloudConfiguration == null) {
360                 throw new ValidationException ("cloudConfiguration");
361         }
362
363         if (cloudConfiguration != null) {
364                 if (empty (cloudConfiguration.getLcpCloudRegionId ())) {
365                         throw new ValidationException ("lcpCloudRegionId");
366                 }
367                 if (empty (cloudConfiguration.getTenantId ())) {
368                         throw new ValidationException ("tenantId");
369                 }
370         }
371
372
373         if (requestScope.equalsIgnoreCase (ModelType.service.name ()) && action == Action.createInstance) {
374                 if (requestParameters == null) {
375                         throw new ValidationException ("requestParameters");
376                 }
377                 if (empty (requestParameters.getSubscriptionServiceType ())) {
378                         throw new ValidationException ("subscriptionServiceType");
379                 }
380         }
381         
382         if (this.reqVersion > 4 && requestScope.equalsIgnoreCase (ModelType.service.name ()) && action == Action.createInstance) {
383                 SubscriberInfo subscriberInfo = sir.getRequestDetails ().getSubscriberInfo();
384                 if (subscriberInfo == null) {
385                         throw new ValidationException ("subscriberInfo");
386                 }
387                 if (empty (subscriberInfo.getGlobalSubscriberId ())) {
388                         throw new ValidationException ("globalSubscriberId");
389                 }
390         }
391
392         if(requestScope.equalsIgnoreCase(ModelType.service.name())){
393                 this.serviceInstanceType = modelInfo.getModelName();
394         }
395
396         if(requestScope.equalsIgnoreCase(ModelType.network.name())){
397                 this.networkType = modelInfo.getModelName();
398         }
399
400         // Verify instanceName existence and format except for macro serviceInstance
401         if (this.reqVersion < 3 && requestScope.equalsIgnoreCase (ModelType.service.name ()) && empty (requestInfo.getInstanceName ()) && action == Action.createInstance) {
402                 throw new ValidationException ("instanceName");
403         }
404
405         if (!empty (requestInfo.getInstanceName ())) {
406                 if (!requestInfo.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) {
407                         throw new ValidationException ("instanceName format");
408                 }
409         }
410
411         if (empty (requestInfo.getProductFamilyId ()))  {
412                 // Mandatory for vnf Create(aLaCarte=true), Network Create(aLaCarte=true) and network update
413                 //Mandatory for macro request create service instance
414                 if((requestScope.equalsIgnoreCase (ModelType.vnf.name ()) && action == Action.createInstance) || 
415                         (requestScope.equalsIgnoreCase (ModelType.network.name ()) && (action == Action.createInstance || action == Action.updateInstance)) ||
416                         (this.reqVersion > 3 && !this.aLaCarteFlag && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.createInstance)) {
417                 throw new ValidationException ("productFamilyId");
418         }
419         }
420        
421         //required for all operations in V4
422         if(empty(requestInfo.getRequestorId()) && this.reqVersion > 3) {
423                 throw new ValidationException ("requestorId");
424         }
425
426         if (empty (requestInfo.getSource ())) {
427                 throw new ValidationException ("source");
428         }
429
430
431         RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
432
433         String serviceModelName = null;
434         String vnfModelName = null;
435         String asdcServiceModelVersion = null;
436         String volumeGroupId = null;
437         boolean isRelatedServiceInstancePresent = false;
438         boolean isRelatedVnfInstancePresent = false;
439
440         if (instanceList != null) {
441                 for(RelatedInstanceList relatedInstanceList : instanceList){
442                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
443
444                         ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo ();
445                                 if (relatedInstanceModelInfo == null) {
446                                 throw new ValidationException ("modelInfo in relatedInstance");
447                         }
448
449                         if (relatedInstanceModelInfo.getModelType () == null) {
450                                 throw new ValidationException ("modelType in relatedInstance");
451                         }
452
453
454                         if (!empty (relatedInstance.getInstanceName ())) {
455                         if (!relatedInstance.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) {
456                                 throw new ValidationException ("instanceName format in relatedInstance");
457                         }
458                     }
459
460                         if (empty (relatedInstance.getInstanceId ())) {
461                                 throw new ValidationException ("instanceId in relatedInstance");
462                         }
463
464                         if (!UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) {
465                                 throw new ValidationException ("instanceId format in relatedInstance");
466                         }
467
468
469                         if (action != Action.deleteInstance) {
470                                 if(!relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {
471
472                                         if(empty (relatedInstanceModelInfo.getModelInvariantId ())) {
473                                         throw new ValidationException ("modelInvariantId in relatedInstance");
474                                         } else if(this.reqVersion > 3 && empty(relatedInstanceModelInfo.getModelVersionId ())) {
475                                                 throw new ValidationException("modelVersionId in relatedInstance");
476                                         } else if(empty(relatedInstanceModelInfo.getModelName ())) {
477                                                 throw new ValidationException ("modelName in relatedInstance");
478                                         } else if (empty (relatedInstanceModelInfo.getModelVersion ())) {
479                                                 throw new ValidationException ("modelVersion in relatedInstance");
480                                         }
481                                 }
482
483                                 if (!empty (relatedInstanceModelInfo.getModelInvariantId ()) &&
484                                                 !UUIDChecker.isValidUUID (relatedInstanceModelInfo.getModelInvariantId ())) {
485                                         throw new ValidationException ("modelInvariantId format in relatedInstance");
486                                 }
487                                 }
488
489                         if (empty (relatedInstanceModelInfo.getModelCustomizationName ()) && relatedInstanceModelInfo.getModelType ().equals (ModelType.vnf) ) {
490                                 if(this.reqVersion >=3 && empty (relatedInstanceModelInfo.getModelCustomizationId()) && action != Action.deleteInstance) {
491                                         throw new ValidationException ("modelCustomizationName or modelCustomizationId in relatedInstance of vnf");
492                                 } else if(this.reqVersion < 3) {
493                                         throw new ValidationException ("modelCustomizationName in relatedInstance");
494                         }
495                         }
496
497                         if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
498                                 isRelatedServiceInstancePresent = true;
499                                 if (!relatedInstance.getInstanceId ().equals (this.sir.getServiceInstanceId ())) {
500                                         throw new ValidationException ("serviceInstanceId matching the serviceInstanceId in request URI");
501                                 }
502                                 serviceModelName = relatedInstanceModelInfo.getModelName ();
503                                 asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion ();
504                         } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
505                                 isRelatedVnfInstancePresent = true;
506                                 if (!relatedInstance.getInstanceId ().equals (this.sir.getVnfInstanceId ())) {
507                                         throw new ValidationException ("vnfInstanceId matching the vnfInstanceId in request URI");
508                                 }
509                                 vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
510                         } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {                              
511                                 volumeGroupId = relatedInstance.getInstanceId ();
512                         }
513                 }
514
515
516                 if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) {
517                         if (!isRelatedServiceInstancePresent) {
518                                 throw new ValidationException ("related service instance for volumeGroup request");
519                         }
520                         if (!isRelatedVnfInstancePresent) {
521                                 throw new ValidationException ("related vnf instance for volumeGroup request");
522                         }
523                         this.serviceInstanceType = serviceModelName;
524                         this.vnfType = serviceModelName + "/" + vnfModelName;
525                         this.asdcServiceModelVersion = asdcServiceModelVersion;
526                 }
527                 else if(requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) {
528                         if (!isRelatedServiceInstancePresent) {
529                                 throw new ValidationException ("related service instance for vfModule request");
530                         }
531                         if (!isRelatedVnfInstancePresent) {
532                                 throw new ValidationException ("related vnf instance for vfModule request");
533                         }
534                         String vfModuleModelName = modelInfo.getModelName ();
535                         this.vfModuleModelName = vfModuleModelName;
536                         this.serviceInstanceType = serviceModelName;
537                         this.vnfType = serviceModelName + "/" + vnfModelName;
538                         this.asdcServiceModelVersion = asdcServiceModelVersion;
539                         this.vfModuleType = vnfType + "::" + vfModuleModelName;
540                         this.sir.setVolumeGroupInstanceId (volumeGroupId);
541                 }
542                 else if (requestScope.equalsIgnoreCase (ModelType.vnf.name ())) {
543                         if (!isRelatedServiceInstancePresent) {
544                                 throw new ValidationException ("related service instance for vnf request");
545                         }
546                         this.vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();
547                }
548         }
549         else if ((( requestScope.equalsIgnoreCase(ModelType.vnf.name ()) || requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ()) ) && (action == Action.createInstance)) ||
550                         (this.reqVersion > 2 && (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) && action == Action.updateInstance)){
551                  msoLogger.debug ("related instance exception");
552                 throw new ValidationException ("related instances");
553         }
554
555     }
556
557     void parseOrchestration (ServiceInstancesRequest sir) throws ValidationException {
558
559         msoLogger.debug ("Validating the Orchestration request");
560
561         this.sir = sir;
562
563         try{
564                 ObjectMapper mapper = new ObjectMapper();
565                 //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
566                 requestJSON = mapper.writeValueAsString(sir.getRequestDetails());
567
568         } catch(Exception e){
569                 throw new ValidationException ("Parse ServiceInstanceRequest to JSON string", e);
570         }
571
572         this.requestInfo = sir.getRequestDetails().getRequestInfo();
573
574         if (this.requestInfo == null) {
575             throw new ValidationException ("requestInfo");
576         }
577
578         if (empty (requestInfo.getSource ())) {
579                 throw new ValidationException ("source");
580         }
581         if (empty (requestInfo.getRequestorId ())) {
582                 throw new ValidationException ("requestorId");
583         }
584     }
585
586     public Map<String, List<String>> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException {
587
588         String queryParam = null;
589         Map<String, List<String>> orchestrationFilterParams = new HashMap<>();
590
591
592         for (Entry<String,List<String>> entry : queryParams.entrySet()) {
593             queryParam = entry.getKey();
594
595             try{
596                   if("filter".equalsIgnoreCase(queryParam)){
597                           for(String value : entry.getValue()) {
598                                   StringTokenizer st = new StringTokenizer(value, ":");
599         
600                                   int counter=0;
601                                   String mapKey=null;
602                                   List<String> orchestrationList = new ArrayList<>();
603                                   while (st.hasMoreElements()) {
604                                           if(counter == 0){
605                                                   mapKey = st.nextElement() + "";
606                                           } else{
607                                                   orchestrationList.add(st.nextElement() + "");
608                                           }
609                                          counter++;
610                                   }
611                                   orchestrationFilterParams.put(mapKey, orchestrationList);
612                           }
613                   }
614
615             }catch(Exception e){
616                 //msoLogger.error (MessageEnum.APIH_VALIDATION_ERROR, e);
617                 throw new ValidationException ("QueryParam ServiceInfo", e);
618
619                 }
620
621         }
622
623
624         return orchestrationFilterParams;
625   }
626
627     public void createRequestRecord (Status status, Action action) {
628
629         Session session = null;
630         try {
631
632             session = requestsDbSessionFactoryManager.getSessionFactory ().openSession ();
633             session.beginTransaction ();
634
635             if (null == sir) {
636                 sir = new ServiceInstancesRequest ();
637             }
638
639             InfraActiveRequests aq = new InfraActiveRequests ();
640             aq.setRequestId (requestId);
641
642             aq.setRequestAction(action.name());
643             aq.setAction(action.name());
644
645             Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
646
647             aq.setStartTime (startTimeStamp);
648
649             if (requestInfo != null) {
650
651                 if(requestInfo.getSource() != null){
652                         aq.setSource(requestInfo.getSource());
653                 }
654                 if(requestInfo.getCallbackUrl() != null){
655                         aq.setCallBackUrl(requestInfo.getCallbackUrl());
656                 }
657                 if(requestInfo.getCorrelator() != null){
658                         aq.setCorrelator(requestInfo.getCorrelator());
659                 }
660
661                 if(requestInfo.getRequestorId() != null) {
662                         aq.setRequestorId(requestInfo.getRequestorId());
663                 }
664             }
665
666             if (modelInfo != null) {
667                 aq.setRequestScope(requestScope);
668             }
669
670             if (cloudConfiguration != null) {
671                 if(cloudConfiguration.getLcpCloudRegionId() != null) {
672                         aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId());
673                 }
674
675                 if(cloudConfiguration.getTenantId() != null) {
676                         aq.setTenantId(cloudConfiguration.getTenantId());
677                 }
678
679             }
680
681             if(sir.getServiceInstanceId() != null){
682                 aq.setServiceInstanceId(sir.getServiceInstanceId());
683             }
684
685             if(sir.getVnfInstanceId() != null){
686                 aq.setVnfId(sir.getVnfInstanceId());
687             }
688
689
690             if(ModelType.service.name().equalsIgnoreCase(requestScope)){
691                 if(requestInfo.getInstanceName() != null){
692                         aq.setServiceInstanceName(requestInfo.getInstanceName());
693                 }
694             }
695
696             if(ModelType.network.name().equalsIgnoreCase(requestScope)){
697                 aq.setNetworkName(requestInfo.getInstanceName());
698                 aq.setNetworkType(networkType);
699                 aq.setNetworkId(sir.getNetworkInstanceId());
700             }
701
702             if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)){
703                 aq.setVolumeGroupId(sir.getVolumeGroupInstanceId());
704                 aq.setVolumeGroupName(requestInfo.getInstanceName());
705                 aq.setVnfType(vnfType);
706
707             }
708
709             if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)){
710                 aq.setVfModuleName(requestInfo.getInstanceName());
711                 aq.setVfModuleModelName(modelInfo.getModelName());
712                 aq.setVfModuleId(sir.getVfModuleInstanceId());
713                 aq.setVolumeGroupId(sir.getVolumeGroupInstanceId());
714                 aq.setVnfType(vnfType);
715
716             }
717
718             if(ModelType.vnf.name().equalsIgnoreCase(requestScope)){
719                 aq.setVnfName(requestInfo.getInstanceName());
720                                 if (null != sir.getRequestDetails()) {
721                                         RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
722
723                                         if (instanceList != null) {
724
725                                                 for(RelatedInstanceList relatedInstanceList : instanceList){
726
727                                                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
728                                                         if(relatedInstance.getModelInfo().getModelType().equals(ModelType.service)){
729                                                                 aq.setVnfType(vnfType);
730                                                         }
731                                                 }
732                                         }
733                                 }
734             }
735
736             aq.setRequestBody (this.requestJSON);
737
738             aq.setRequestStatus (status.toString ());
739             aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
740
741             if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
742                 aq.setStatusMessage (this.errorMessage);
743                 aq.setResponseBody (this.responseBody);
744                 aq.setProgress(new Long(100));
745
746                 Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis());
747                 aq.setEndTime (endTimeStamp);
748             }
749
750             msoLogger.debug ("About to insert a record");
751
752             session.save (aq);
753             session.getTransaction ().commit ();
754             session.close ();
755         } catch (Exception e) {
756                 msoLogger.error (MessageEnum.APIH_DB_INSERT_EXC, "", "", MsoLogger.ErrorCode.DataError, "Exception when creation record request", e);
757             if (session != null) {
758                 session.close ();
759             }
760             if (!status.equals (Status.FAILED)) {
761                 throw e;
762             }
763         }
764     }
765
766     public void updateFinalStatus (Status status) {
767         int result = 0;
768         try {
769             result = (RequestsDatabase.getInstance()).updateInfraFinalStatus (requestId,
770                                                               status.toString (),
771                                                               this.errorMessage,
772                                                               this.progress,
773                                                               this.responseBody,
774                                                               Constants.MODIFIED_BY_APIHANDLER);
775         } catch (Exception e) {
776                 msoLogger.error(MessageEnum.APIH_DB_UPDATE_EXC, e.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "Exception when updating record in DB");
777             msoLogger.debug ("Exception: ", e);
778         }
779     }
780
781     public Response buildResponse (int httpResponseCode, String errorCode, InfraActiveRequests inProgress) {
782         return buildResponseWithError (httpResponseCode, errorCode, inProgress, null);
783     }
784
785     public Response buildResponseWithError (int httpResponseCode,
786                                             String errorCode,
787                                             InfraActiveRequests inProgress,
788                                             String errorString) {
789
790
791
792         // Log the failed request into the MSO Requests database
793
794         return Response.status (httpResponseCode).entity (null).build ();
795
796     }
797
798     public Response buildResponseFailedValidation (int httpResponseCode, String exceptionMessage) {
799
800
801
802         return Response.status (httpResponseCode).entity (null).build ();
803     }
804
805     public String getRequestUri () {
806         return requestUri;
807     }
808
809     public void setRequestUri (String requestUri) {
810         this.requestUri = requestUri;
811     }
812
813     public VnfInputs getVnfInputs () {
814         return vnfInputs;
815     }
816
817     public RequestInfo getRequestInfo () {
818         return requestInfo;
819     }
820
821     public String getResponseBody () {
822         return responseBody;
823     }
824
825     public void setResponseBody (String responseBody) {
826         this.responseBody = responseBody;
827     }
828
829     public String getHttpResponse () {
830         return httpResponse;
831     }
832
833     public void setHttpResponse (String httpResponse) {
834         this.httpResponse = httpResponse;
835     }
836
837     public String getRequestId () {
838         return requestId;
839     }
840
841     public String getRequestXML () {
842         return requestXML;
843     }
844
845     public void setRequestXML (String requestXML) {
846         this.requestXML = requestXML;
847     }
848
849     public RequestStatusType getStatus () {
850         return status;
851     }
852
853     public String getServiceType () {
854         if (this.vnfInputs.getServiceType () != null)
855                 return this.vnfInputs.getServiceType ();
856         if (this.vnfInputs.getServiceId () != null)
857                 return this.vnfInputs.getServiceId ();
858         return null;
859     }
860
861     public void setStatus (RequestStatusType status) {
862         this.status = status;
863         switch (status) {
864         case FAILED:
865         case COMPLETE:
866                 this.progress = Constants.PROGRESS_REQUEST_COMPLETED;
867                 break;
868         case IN_PROGRESS:
869                 this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS;
870                 break;
871         }
872     }
873
874     public ModelInfo getModelInfo() {
875         return modelInfo;
876     }
877
878     public ServiceInstancesRequest getServiceInstancesRequest() {
879         return sir;
880     }
881
882     public String getServiceInstanceType () {
883         return serviceInstanceType;
884     }
885
886     public String getNetworkType () {
887         return networkType;
888     }
889
890     public String getVnfType () {
891         return vnfType;
892     }
893
894     public String getVfModuleModelName () {
895         return vfModuleModelName;
896     }
897
898     public String getVfModuleType () {
899         return vfModuleType;
900     }
901
902     public String getAsdcServiceModelVersion () {
903         return asdcServiceModelVersion;
904     }
905
906     public static String domToStr (Document doc) {
907         if (doc == null) {
908             return null;
909         }
910
911         try {
912             StringWriter sw = new StringWriter ();
913             StreamResult sr = new StreamResult (sw);
914             TransformerFactory tf = TransformerFactory.newInstance ();
915             Transformer t = tf.newTransformer ();
916             t.setOutputProperty (OutputKeys.STANDALONE, "yes");
917             NodeList nl = doc.getDocumentElement ().getChildNodes ();
918             DOMSource source = null;
919             for (int x = 0; x < nl.getLength (); x++) {
920                 Node e = nl.item (x);
921                 if (e instanceof Element) {
922                     source = new DOMSource (e);
923                     break;
924                 }
925             }
926             if (source != null) {
927                 t.transform (source, sr);
928
929                 String s = sw.toString ();
930                 return s;
931             }
932
933             return null;
934
935         } catch (Exception e) {
936             msoLogger.error (MessageEnum.APIH_DOM2STR_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception in domToStr", e);
937         }
938         return null;
939     }
940
941     public void addBPMNSpecificInputs(String personaModelId, String personaModelVersion, Boolean isBaseVfModule,
942                         String vnfPersonaModelId, String vnfPersonaModelVersion) {
943         vnfInputs.setPersonaModelId(personaModelId);
944         vnfInputs.setPersonaModelVersion(personaModelVersion);
945         vnfInputs.setIsBaseVfModule(isBaseVfModule);
946         vnfInputs.setVnfPersonaModelId(vnfPersonaModelId);
947         vnfInputs.setVnfPersonaModelVersion(vnfPersonaModelVersion);
948
949         this.vnfReq.setVnfInputs(vnfInputs);
950
951           StringWriter stringWriter = new StringWriter ();
952           try {
953               JAXBContext jaxbContext = JAXBContext.newInstance (VnfRequest.class);
954               Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
955
956               // output pretty printed
957               jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
958
959               jaxbMarshaller.marshal (this.vnfReq, stringWriter);
960
961           } catch (JAXBException e) {
962               msoLogger.debug ("Exception: ", e);
963           }
964
965           this.requestXML = stringWriter.toString ();
966           msoLogger.debug("REQUEST XML to BPEL: " + this.requestXML);
967
968
969     }
970
971     private static boolean empty(String s) {
972           return (s == null || s.trim().isEmpty());
973     }
974
975     public String getRequestJSON() throws JsonGenerationException, JsonMappingException, IOException {
976         ObjectMapper mapper = new ObjectMapper();
977         mapper.setSerializationInclusion(Inclusion.NON_NULL);
978         //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
979         msoLogger.debug ("building sir from object " + sir);
980         requestJSON = mapper.writeValueAsString(sir);
981         
982         // Perform mapping from VID-style modelInfo fields to ASDC-style modelInfo fields
983         
984         msoLogger.debug("REQUEST JSON before mapping: " + requestJSON);
985         // modelUuid = modelVersionId
986         requestJSON = requestJSON.replaceAll("\"modelVersionId\":","\"modelUuid\":");
987         // modelCustomizationUuid = modelCustomizationId
988         requestJSON = requestJSON.replaceAll("\"modelCustomizationId\":","\"modelCustomizationUuid\":");
989         // modelInstanceName = modelCustomizationName
990         requestJSON = requestJSON.replaceAll("\"modelCustomizationName\":","\"modelInstanceName\":");
991         // modelInvariantUuid = modelInvariantId 
992         requestJSON = requestJSON.replaceAll("\"modelInvariantId\":","\"modelInvariantUuid\":");        
993         msoLogger.debug("REQUEST JSON after mapping: " + requestJSON);
994         
995         return requestJSON;
996     }
997
998         public boolean getALaCarteFlag() {
999                 return aLaCarteFlag;
1000         }
1001
1002         public void setaLaCarteFlag(boolean aLaCarteFlag) {
1003                 this.aLaCarteFlag = aLaCarteFlag;
1004         }
1005
1006         public int getReqVersion() {
1007                 return reqVersion;
1008         }
1009
1010         public void setReqVersion(int reqVersion) {
1011                 this.reqVersion = reqVersion;
1012         }
1013 }