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