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