de7d26379ca05b9745d079c4156f5b490205ad83
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / 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  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.so.apihandlerinfra;
25
26 import java.io.IOException;
27 import java.io.StringWriter;
28 import java.net.URL;
29 import java.sql.Timestamp;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.Optional;
36 import java.util.StringTokenizer;
37
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Response;
40 import javax.xml.XMLConstants;
41 import javax.xml.transform.OutputKeys;
42 import javax.xml.transform.Transformer;
43 import javax.xml.transform.TransformerFactory;
44 import javax.xml.transform.dom.DOMSource;
45 import javax.xml.transform.stream.StreamResult;
46
47 import org.onap.so.apihandler.common.ResponseBuilder;
48 import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest;
49 import org.onap.so.apihandlerinfra.validation.MembersValidation;
50 import org.onap.so.apihandlerinfra.validation.ApplyUpdatedConfigValidation;
51 import org.onap.so.apihandlerinfra.validation.CloudConfigurationValidation;
52 import org.onap.so.apihandlerinfra.validation.ConfigurationParametersValidation;
53 import org.onap.so.apihandlerinfra.validation.InPlaceSoftwareUpdateValidation;
54 import org.onap.so.apihandlerinfra.validation.InstanceIdMapValidation;
55 import org.onap.so.apihandlerinfra.validation.ModelInfoValidation;
56 import org.onap.so.apihandlerinfra.validation.PlatformLOBValidation;
57 import org.onap.so.apihandlerinfra.validation.ProjectOwningEntityValidation;
58 import org.onap.so.apihandlerinfra.validation.RelatedInstancesValidation;
59 import org.onap.so.apihandlerinfra.validation.RequestInfoValidation;
60 import org.onap.so.apihandlerinfra.validation.RequestParametersValidation;
61 import org.onap.so.apihandlerinfra.validation.RequestScopeValidation;
62 import org.onap.so.apihandlerinfra.validation.SubscriberInfoValidation;
63 import org.onap.so.apihandlerinfra.validation.UserParamsValidation;
64 import org.onap.so.apihandlerinfra.validation.ValidationInformation;
65 import org.onap.so.apihandlerinfra.validation.ValidationRule;
66 import org.onap.so.apihandlerinfra.vnfbeans.RequestStatusType;
67 import org.onap.so.apihandlerinfra.vnfbeans.VnfInputs;
68 import org.onap.so.apihandlerinfra.vnfbeans.VnfRequest;
69 import org.onap.so.db.request.beans.InfraActiveRequests;
70 import org.onap.so.db.request.client.RequestsDbClient;
71 import org.onap.so.exceptions.ValidationException;
72 import org.onap.so.logger.ErrorCode;
73 import org.onap.so.logger.LogConstants;
74 import org.onap.so.logger.MessageEnum;
75 import org.onap.so.serviceinstancebeans.CloudConfiguration;
76 import org.onap.so.serviceinstancebeans.InstanceDirection;
77 import org.onap.so.serviceinstancebeans.ModelInfo;
78 import org.onap.so.serviceinstancebeans.ModelType;
79 import org.onap.so.serviceinstancebeans.PolicyException;
80 import org.onap.so.serviceinstancebeans.RelatedInstance;
81 import org.onap.so.serviceinstancebeans.RelatedInstanceList;
82 import org.onap.so.serviceinstancebeans.RequestError;
83 import org.onap.so.serviceinstancebeans.RequestInfo;
84 import org.onap.so.serviceinstancebeans.RequestParameters;
85 import org.onap.so.serviceinstancebeans.Service;
86 import org.onap.so.serviceinstancebeans.ServiceException;
87 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
90 import org.slf4j.MDC;
91 import org.springframework.beans.factory.annotation.Autowired;
92 import org.springframework.stereotype.Component;
93 import org.w3c.dom.Document;
94 import org.w3c.dom.Element;
95 import org.w3c.dom.Node;
96 import org.w3c.dom.NodeList;
97
98 import com.fasterxml.jackson.annotation.JsonInclude.Include;
99 import com.fasterxml.jackson.core.JsonGenerationException;
100 import com.fasterxml.jackson.databind.JsonMappingException;
101 import com.fasterxml.jackson.databind.ObjectMapper;
102
103
104 @Component
105 public class MsoRequest {
106       
107         @Autowired
108         private RequestsDbClient requestsDbClient;
109         
110         @Autowired
111         private ResponseBuilder builder;
112     
113     private static Logger logger = LoggerFactory.getLogger(MsoRequest.class);
114     
115     public Response buildServiceErrorResponse (int httpResponseCode, MsoException exceptionType, 
116                 String errorText, String messageId, List<String> variables, String version) {
117         
118         if(errorText.length() > 1999){
119                 errorText = errorText.substring(0, 1999);
120         }
121
122         RequestError re = new RequestError();
123
124         if("PolicyException".equals(exceptionType.name())){
125
126                 PolicyException pe = new PolicyException();
127                 pe.setMessageId(messageId);
128                 pe.setText(errorText);
129                 if(variables != null){
130                         for(String variable: variables){
131                                 pe.getVariables().add(variable);
132                         }
133                 }
134                 re.setPolicyException(pe);
135
136         } else {
137
138                 ServiceException se = new ServiceException();
139                 se.setMessageId(messageId);
140                 se.setText(errorText);
141                 if(variables != null){
142                                 for(String variable: variables){
143                                         se.getVariables().add(variable);
144                                 }
145                         }
146                 re.setServiceException(se);
147         }
148
149         String requestErrorStr = null;
150
151         try{
152                 ObjectMapper mapper = new ObjectMapper();
153                 mapper.setSerializationInclusion(Include.NON_DEFAULT);
154                 requestErrorStr = mapper.writeValueAsString(re);
155         }catch(Exception e){
156                                         logger.error("{} {} {}", MessageEnum.APIH_VALIDATION_ERROR.toString(), ErrorCode.DataError.getValue(),
157                                                         "Exception in buildServiceErrorResponse writing exceptionType to string ", e);
158                                 }
159
160         return builder.buildResponse(httpResponseCode, null, requestErrorStr, version);
161     }
162
163    
164
165     // Parse request JSON
166     public void parse (ServiceInstancesRequest sir, HashMap<String,String> instanceIdMap, Actions action, String version,
167                 String originalRequestJSON, int reqVersion, Boolean aLaCarteFlag) throws ValidationException, IOException {
168         
169         logger.debug ("Validating the Service Instance request");
170         List<ValidationRule> rules = new ArrayList<>();
171         logger.debug ("Incoming version is: {} coverting to int: {}", version, reqVersion);
172             RequestParameters requestParameters = sir.getRequestDetails().getRequestParameters();
173         ValidationInformation info = new ValidationInformation(sir, instanceIdMap, action,
174                         reqVersion, aLaCarteFlag, requestParameters);
175         
176         rules.add(new InstanceIdMapValidation());
177         
178         if(reqVersion >= 6 && action == Action.inPlaceSoftwareUpdate){
179                 rules.add(new InPlaceSoftwareUpdateValidation());
180         }else if(reqVersion >= 6 && action == Action.applyUpdatedConfig){
181                 rules.add(new ApplyUpdatedConfigValidation());
182         }else if(action == Action.addMembers || action == Action.removeMembers){
183                 rules.add(new MembersValidation());
184         }else{
185                 rules.add(new RequestScopeValidation());
186                 rules.add(new RequestParametersValidation());
187                 rules.add(new RequestInfoValidation());
188                 rules.add(new ModelInfoValidation());
189                 rules.add(new CloudConfigurationValidation());
190                 rules.add(new SubscriberInfoValidation());
191                 rules.add(new PlatformLOBValidation());
192                 rules.add(new ProjectOwningEntityValidation());
193                 rules.add(new RelatedInstancesValidation());
194                 rules.add(new ConfigurationParametersValidation());
195         } 
196             if(reqVersion >= 7 && requestParameters != null && requestParameters.getUserParams() != null){
197                 for(Map<String, Object> params : requestParameters.getUserParams()){
198                         if(params.containsKey("service")){
199                                 ObjectMapper obj = new ObjectMapper();
200                                         String input = obj.writeValueAsString(params.get("service"));
201                                         Service validate = obj.readValue(input, Service.class);
202                                         info.setUserParams(validate);
203                                         rules.add(new UserParamsValidation());
204                                         break;
205                         }
206                 }
207             }
208             for(ValidationRule rule : rules){
209                 rule.validate(info);
210         }
211     }
212     void parseOrchestration (ServiceInstancesRequest sir) throws ValidationException {
213         RequestInfo requestInfo = sir.getRequestDetails().getRequestInfo();
214
215         if (requestInfo == null) {
216             throw new ValidationException ("requestInfo");
217         }
218
219         if (empty (requestInfo.getSource ())) {
220                 throw new ValidationException ("source");
221         }
222         if (empty (requestInfo.getRequestorId ())) {
223                 throw new ValidationException ("requestorId");
224         }
225     }
226     public Map<String, List<String>> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException {
227
228         String queryParam = null;
229         Map<String, List<String>> orchestrationFilterParams = new HashMap<>();
230
231
232         for (Entry<String,List<String>> entry : queryParams.entrySet()) {
233             queryParam = entry.getKey();
234
235             try{
236                   if("filter".equalsIgnoreCase(queryParam)){
237                           for(String value : entry.getValue()) {
238                                   StringTokenizer st = new StringTokenizer(value, ":");
239         
240                                   int counter=0;
241                                   String mapKey=null;
242                                   List<String> orchestrationList = new ArrayList<>();
243                                   while (st.hasMoreElements()) {
244                                           if(counter == 0){
245                                                   mapKey = st.nextElement() + "";
246                                           } else{
247                                                   orchestrationList.add(st.nextElement() + "");
248                                           }
249                                          counter++;
250                                   }
251                                   orchestrationFilterParams.put(mapKey, orchestrationList);
252                           }
253                   }
254
255             }catch(Exception e){
256                 throw new ValidationException ("QueryParam ServiceInfo", e);
257                 }
258
259         }
260
261
262         return orchestrationFilterParams;
263   }
264
265     public InfraActiveRequests createRequestObject (ServiceInstancesRequest servInsReq, Actions action, String requestId,
266                  Status status, String originalRequestJSON, String requestScope) {
267         InfraActiveRequests aq = new InfraActiveRequests ();
268         try {
269             if (null == servInsReq) {
270                 servInsReq = new ServiceInstancesRequest ();
271             }
272             String networkType = "";
273             String vnfType = "";
274             aq.setRequestId (requestId);
275             aq.setRequestAction(action.toString());
276             aq.setAction(action.toString());
277             aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
278
279             Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
280
281             aq.setStartTime (startTimeStamp);
282             if(requestScope.equals(ModelType.instanceGroup.name()) && action == Action.deleteInstance){
283                 aq.setRequestScope(requestScope);
284             }else{
285                     RequestInfo requestInfo =servInsReq.getRequestDetails().getRequestInfo();
286                     if (requestInfo != null) {
287                         
288                         if(requestInfo.getSource() != null){
289                                 aq.setSource(requestInfo.getSource());
290                         }
291                         if(requestInfo.getCallbackUrl() != null){
292                                 aq.setCallBackUrl(requestInfo.getCallbackUrl());
293                         }
294                         if(requestInfo.getCorrelator() != null){
295                                 aq.setCorrelator(requestInfo.getCorrelator());
296                         }
297         
298                         if(requestInfo.getRequestorId() != null) {
299                                 aq.setRequestorId(requestInfo.getRequestorId());
300                         }
301                     }
302         
303                     if (servInsReq.getRequestDetails().getModelInfo() != null  ||  (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig)) {
304                         aq.setRequestScope(requestScope);
305                     }
306         
307                     if (servInsReq.getRequestDetails().getCloudConfiguration() != null) {
308                         CloudConfiguration cloudConfiguration = servInsReq.getRequestDetails().getCloudConfiguration();
309                         if(cloudConfiguration.getLcpCloudRegionId() != null) {
310                                 aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId());
311                         }
312         
313                         if(cloudConfiguration.getTenantId() != null) {
314                                 aq.setTenantId(cloudConfiguration.getTenantId());
315                         }
316         
317                     }
318         
319                     if(servInsReq.getServiceInstanceId() != null){
320                         aq.setServiceInstanceId(servInsReq.getServiceInstanceId());
321                     }
322         
323                     if(servInsReq.getVnfInstanceId() != null){
324                         aq.setVnfId(servInsReq.getVnfInstanceId());
325                     }
326         
327                     if(ModelType.service.name().equalsIgnoreCase(requestScope)){
328                         if(servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null){
329                                 aq.setServiceInstanceName(requestInfo.getInstanceName());
330                         }
331                     }
332         
333                     if(ModelType.network.name().equalsIgnoreCase(requestScope)){
334                         aq.setNetworkName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName());
335                         aq.setNetworkType(networkType);
336                         aq.setNetworkId(servInsReq.getNetworkInstanceId());
337                     }
338         
339                     if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)){
340                         aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId());
341                         aq.setVolumeGroupName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName());
342                         aq.setVnfType(vnfType);
343         
344                     }
345         
346                     if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)){
347                         aq.setVfModuleName(requestInfo.getInstanceName());
348                         aq.setVfModuleModelName(servInsReq.getRequestDetails().getModelInfo().getModelName());
349                         aq.setVfModuleId(servInsReq.getVfModuleInstanceId());
350                         aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId());
351                         aq.setVnfType(vnfType);
352         
353                     }
354                     
355                     if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
356                         aq.setConfigurationId(servInsReq.getConfigurationId());
357                         aq.setConfigurationName(requestInfo.getInstanceName());
358                     }
359                     if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.name())){
360                         aq.setInstanceGroupId(servInsReq.getInstanceGroupId());
361                         aq.setInstanceGroupName(requestInfo.getInstanceName());
362                     }
363                     if(ModelType.vnf.name().equalsIgnoreCase(requestScope)){
364                         aq.setVnfName(requestInfo.getInstanceName());
365                                         if (null != servInsReq.getRequestDetails()) {
366                                                 RelatedInstanceList[] instanceList = servInsReq.getRequestDetails().getRelatedInstanceList();
367         
368                                                 if (instanceList != null) {
369         
370                                                         for(RelatedInstanceList relatedInstanceList : instanceList){
371         
372                                                                 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
373                                                                 if(relatedInstance.getModelInfo().getModelType().equals(ModelType.service)){
374                                                                         aq.setVnfType(vnfType);
375                                                                 }
376                                                         }
377                                                 }
378                                         }
379                     }
380             }
381
382             aq.setRequestBody (originalRequestJSON);
383
384             aq.setRequestStatus (status.toString ());
385             aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);           
386         } catch (Exception e) {
387                                         logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(),
388                                                 "Exception when creation record request", e);
389
390                                         if (!status.equals (Status.FAILED)) {
391                 throw e;
392             }
393         }
394         return aq;
395     }
396     
397     public InfraActiveRequests createRequestObject (TasksRequest taskRequest, Action action, String requestId,
398                  Status status, String originalRequestJSON) {
399         InfraActiveRequests aq = new InfraActiveRequests ();
400        try {
401         
402            org.onap.so.apihandlerinfra.tasksbeans.RequestInfo requestInfo = taskRequest.getRequestDetails().getRequestInfo();
403            aq.setRequestId (requestId);
404            aq.setRequestAction(action.name());
405            aq.setAction(action.name());
406            aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL));
407
408            Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
409
410            aq.setStartTime (startTimeStamp);           
411            if (requestInfo != null) {
412                 
413                 if(requestInfo.getSource() != null){
414                         aq.setSource(requestInfo.getSource());
415                 }           
416
417                 if(requestInfo.getRequestorId() != null) {
418                         aq.setRequestorId(requestInfo.getRequestorId());
419                 }
420            }  
421
422            aq.setRequestBody (originalRequestJSON);
423            aq.setRequestStatus (status.toString ());
424            aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
425                   
426        } catch (Exception e) {
427                                  logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(),
428                                          "Exception when creation record request", e);
429
430                                  if (!status.equals (Status.FAILED)) {
431                throw e;
432            }
433        }
434        return aq;
435    }
436     
437     public void createErrorRequestRecord (Status status, String requestId, String errorMessage, Actions action, String requestScope, String requestJSON) {
438         try {
439             InfraActiveRequests request = new InfraActiveRequests(requestId);
440             Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
441             request.setStartTime (startTimeStamp);
442             request.setRequestStatus(status.toString());
443             request.setStatusMessage(errorMessage);
444             request.setProgress((long) 100);
445             request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
446             request.setRequestAction(action.toString());
447             request.setRequestScope(requestScope);
448             request.setRequestBody(requestJSON);
449             Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
450             request.setEndTime(endTimeStamp);
451             request.setRequestUrl(MDC.get(LogConstants.HTTP_URL));            
452                         requestsDbClient.save(request);
453         } catch (Exception e) {
454                                         logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(),
455                                                 ErrorCode.DataError.getValue(), "Exception when updating record in DB");
456                                         logger.debug("Exception: ", e);
457                                 }
458     }
459     
460     
461
462
463     public Response buildResponse (int httpResponseCode, String errorCode, InfraActiveRequests inProgress) {
464         return buildResponseWithError (httpResponseCode, errorCode, inProgress, null);
465     }
466
467     public Response buildResponseWithError (int httpResponseCode,
468                                             String errorCode,
469                                             InfraActiveRequests inProgress,
470                                             String errorString) {
471
472
473
474         // Log the failed request into the MSO Requests database
475
476         return Response.status (httpResponseCode).entity (null).build ();
477
478     }
479
480     public Response buildResponseFailedValidation (int httpResponseCode, String exceptionMessage) {
481
482         return Response.status (httpResponseCode).entity (null).build ();
483     }
484     
485   
486
487     public String getServiceType (VnfInputs vnfInputs) {
488         if (vnfInputs.getServiceType () != null)
489                 return vnfInputs.getServiceType ();
490         if (vnfInputs.getServiceId () != null)
491                 return vnfInputs.getServiceId ();
492         return null;
493     }
494
495     public long translateStatus (RequestStatusType status) {        
496         switch (status) {
497         case FAILED:
498         case COMPLETE:
499                 return Constants.PROGRESS_REQUEST_COMPLETED;            
500         case IN_PROGRESS:
501                 return Constants.PROGRESS_REQUEST_IN_PROGRESS;
502                 default:
503                         return 0;               
504         }
505     }
506
507     public static String domToStr (Document doc) {
508         if (doc == null) {
509             return null;
510         }
511
512         try {
513             StringWriter sw = new StringWriter ();
514             StreamResult sr = new StreamResult (sw);
515             TransformerFactory tf = TransformerFactory.newInstance ();
516                         tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
517                         tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,"");
518             Transformer t = tf.newTransformer ();
519             t.setOutputProperty (OutputKeys.STANDALONE, "yes");
520             NodeList nl = doc.getDocumentElement ().getChildNodes ();
521             DOMSource source = null;
522             for (int x = 0; x < nl.getLength (); x++) {
523                 Node e = nl.item (x);
524                 if (e instanceof Element) {
525                     source = new DOMSource (e);
526                     break;
527                 }
528             }
529             if (source != null) {
530                 t.transform (source, sr);
531
532                 String s = sw.toString ();
533                 return s;
534             }
535
536             return null;
537
538         } catch (Exception e) {
539                                         logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(),
540                                                 "Exception in domToStr", e);
541                                 }
542         return null;
543     }
544
545     public void addBPMNSpecificInputs(VnfRequest vnfReq, VnfInputs vnfInputs, String personaModelId, String personaModelVersion, Boolean isBaseVfModule,
546                         String vnfPersonaModelId, String vnfPersonaModelVersion) {
547         vnfInputs.setPersonaModelId(personaModelId);
548         vnfInputs.setPersonaModelVersion(personaModelVersion);
549         vnfInputs.setIsBaseVfModule(isBaseVfModule);
550         vnfInputs.setVnfPersonaModelId(vnfPersonaModelId);
551         vnfInputs.setVnfPersonaModelVersion(vnfPersonaModelVersion);
552
553         vnfReq.setVnfInputs(vnfInputs);
554       
555     }
556
557     private static boolean empty(String s) {
558           return (s == null || s.trim().isEmpty());
559     }
560
561     public String getRequestJSON(ServiceInstancesRequest sir) throws JsonGenerationException, JsonMappingException, IOException {
562         ObjectMapper mapper = new ObjectMapper();
563         mapper.setSerializationInclusion(Include.NON_NULL);
564         //mapper.configure(Feature.WRAP_ROOT_VALUE, true);
565         logger.debug ("building sir from object {}", sir);
566         String requestJSON = mapper.writeValueAsString(sir);
567         
568         // Perform mapping from VID-style modelInfo fields to ASDC-style modelInfo fields
569         
570         logger.debug("REQUEST JSON before mapping: {}", requestJSON);
571         // modelUuid = modelVersionId
572         requestJSON = requestJSON.replaceAll("\"modelVersionId\":","\"modelUuid\":");
573         // modelCustomizationUuid = modelCustomizationId
574         requestJSON = requestJSON.replaceAll("\"modelCustomizationId\":","\"modelCustomizationUuid\":");
575         // modelInstanceName = modelCustomizationName
576         requestJSON = requestJSON.replaceAll("\"modelCustomizationName\":","\"modelInstanceName\":");
577         // modelInvariantUuid = modelInvariantId 
578         requestJSON = requestJSON.replaceAll("\"modelInvariantId\":","\"modelInvariantUuid\":");        
579         logger.debug("REQUEST JSON after mapping: {}", requestJSON);
580         
581         return requestJSON;
582     }
583
584
585         public boolean getAlacarteFlag(ServiceInstancesRequest sir) {
586                 if(sir.getRequestDetails().getRequestParameters() != null &&
587                                 sir.getRequestDetails().getRequestParameters().getALaCarte() != null)
588                         return sir.getRequestDetails().getRequestParameters().getALaCarte();
589                 
590                 return false;
591         }
592
593
594         public String getNetworkType(ServiceInstancesRequest sir, String requestScope) {
595                   if(requestScope.equalsIgnoreCase(ModelType.network.name()))
596                         return sir.getRequestDetails().getModelInfo().getModelName();   
597                   else return null;
598         }
599
600
601         public String getServiceInstanceType(ServiceInstancesRequest sir, String requestScope) {
602                  if(requestScope.equalsIgnoreCase(ModelType.network.name()))
603                         return sir.getRequestDetails().getModelInfo().getModelName();   
604                   else return null;             
605         }
606
607
608         public String getSDCServiceModelVersion(ServiceInstancesRequest sir) {
609                 String sdcServiceModelVersion = null;
610                 if(sir.getRequestDetails().getRelatedInstanceList() != null)
611                         for(RelatedInstanceList relatedInstanceList : sir.getRequestDetails().getRelatedInstanceList()){
612                                 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
613                                 ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo ();   
614                                 if(relatedInstanceModelInfo.getModelType().equals(ModelType.service))                                           
615                                         sdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion ();
616                         }
617         return sdcServiceModelVersion;
618         }
619
620
621         public String getVfModuleType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) {       
622         
623         String serviceInstanceType = null;
624         String networkType = null;
625         String vnfType = null;
626         String vfModuleType = null;
627         String vfModuleModelName = null;
628                 ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
629                 RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
630                 String serviceModelName = null;
631         String vnfModelName = null;
632         String asdcServiceModelVersion = null;
633         String volumeGroupId = null;
634         boolean isRelatedServiceInstancePresent = false;
635         boolean isRelatedVnfInstancePresent = false;
636         boolean isSourceVnfPresent = false;
637         boolean isDestinationVnfPresent = false;
638         boolean isConnectionPointPresent = false;       
639
640             if (instanceList != null) {
641                 for(RelatedInstanceList relatedInstanceList : instanceList){
642                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
643                         ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo ();   
644
645                         if (action != Action.deleteInstance) {
646                                 
647                                 if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
648                                         if(InstanceDirection.source.equals(relatedInstance.getInstanceDirection()) && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
649                                                 isSourceVnfPresent = true;
650                                         } else if(InstanceDirection.destination.equals(relatedInstance.getInstanceDirection()) && 
651                                                         (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) && reqVersion == 6))) {
652                                                 isDestinationVnfPresent = true;
653                                         }
654                                 }
655                                 
656                                 if(ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType()) && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
657                                         isConnectionPointPresent = true;
658                                 }
659                         }
660                         
661
662                         if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
663                                 isRelatedServiceInstancePresent = true;                         
664                                 serviceModelName = relatedInstanceModelInfo.getModelName ();
665                                 asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion ();
666                         } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) {
667                                 isRelatedVnfInstancePresent = true;                             
668                                 vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
669                         } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {                              
670                                 volumeGroupId = relatedInstance.getInstanceId ();
671                         }
672                 }
673                 
674                 if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) {                     
675                         serviceInstanceType = serviceModelName;
676                         vnfType = serviceModelName + "/" + vnfModelName;          
677                 }
678                 else if(requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) {         
679                         vfModuleModelName = modelInfo.getModelName ();
680                         serviceInstanceType = serviceModelName;
681                         vnfType = serviceModelName + "/" + vnfModelName;
682                         vfModuleType = vnfType + "::" + vfModuleModelName;
683                         sir.setVolumeGroupInstanceId (volumeGroupId);            
684                 }
685                 else if (requestScope.equalsIgnoreCase (ModelType.vnf.name ()))
686                         vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();                  
687                
688         }     
689         
690                 return vfModuleType;
691
692         }
693         
694         public String getVnfType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) {    
695                 
696         String serviceInstanceType = null;
697         String networkType = null;
698         String vnfType = null;
699         String vfModuleType = null;
700         String vfModuleModelName = null;
701                 ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
702                 RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList();
703                 String serviceModelName = null;
704         String vnfModelName = null;
705         String asdcServiceModelVersion = null;
706         String volumeGroupId = null;
707         boolean isRelatedServiceInstancePresent = false;
708         boolean isRelatedVnfInstancePresent = false;
709         boolean isSourceVnfPresent = false;
710         boolean isDestinationVnfPresent = false;
711         boolean isConnectionPointPresent = false;       
712
713             if (instanceList != null) {
714                 for(RelatedInstanceList relatedInstanceList : instanceList){
715                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
716                         ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo ();   
717
718                         if (action != Action.deleteInstance) {
719                                 
720                                 if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
721                                         if(InstanceDirection.source.equals(relatedInstance.getInstanceDirection()) && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
722                                                 isSourceVnfPresent = true;
723                                         } else if(InstanceDirection.destination.equals(relatedInstance.getInstanceDirection()) && 
724                                                         (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) && reqVersion == 6))) {
725                                                 isDestinationVnfPresent = true;
726                                         }
727                                 }
728                                 
729                                 if(ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType()) && ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
730                                         isConnectionPointPresent = true;
731                                 }
732                         }
733                         
734
735                         if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
736                                 isRelatedServiceInstancePresent = true;                         
737                                 serviceModelName = relatedInstanceModelInfo.getModelName ();
738                                 asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion ();
739                         } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) {
740                                 isRelatedVnfInstancePresent = true;                             
741                                 vnfModelName = relatedInstanceModelInfo.getModelCustomizationName();
742                         } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) {                              
743                                 volumeGroupId = relatedInstance.getInstanceId ();
744                         }
745                 }
746                 
747                 if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) {                     
748                         serviceInstanceType = serviceModelName;
749                         vnfType = serviceModelName + "/" + vnfModelName;          
750                 }
751                 else if(requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) {         
752                         vfModuleModelName = modelInfo.getModelName ();
753                         serviceInstanceType = serviceModelName;
754                         vnfType = serviceModelName + "/" + vnfModelName;
755                         vfModuleType = vnfType + "::" + vfModuleModelName;
756                         sir.setVolumeGroupInstanceId (volumeGroupId);            
757                 }
758                 else if (requestScope.equalsIgnoreCase (ModelType.vnf.name ()))
759                         vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName();                  
760                
761         }     
762         
763                 return vnfType;
764
765         }
766         
767         public Optional<URL> buildSelfLinkUrl(String url, String requestId) {
768                 Optional<URL> selfLinkUrl = Optional.empty();
769                 String version = "";            
770                 try {
771                         URL aUrl = new URL(url);
772                         String aPath = aUrl.getPath();
773                         if (aPath.indexOf("/v") == -1) {
774                                 version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V")+4);
775                         } else {
776                                 version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v")+4);
777                         }
778                         String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId);
779                         selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath));
780                 } catch (Exception e) {
781                         selfLinkUrl = Optional.empty();  // ignore
782                 }
783                 return selfLinkUrl;
784         }       
785 }