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