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