diff options
32 files changed, 4170 insertions, 3334 deletions
diff --git a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java index db639dad0a..3a29247d6e 100644 --- a/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java +++ b/asdc-controller/src/main/java/org/onap/so/asdc/installer/heat/ToscaResourceInstaller.java @@ -10,9 +10,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -24,8 +24,6 @@ package org.onap.so.asdc.installer.heat; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; @@ -37,6 +35,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; + import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.LockAcquisitionException; import org.onap.sdc.api.notification.IArtifactInfo; @@ -143,2323 +142,2227 @@ import org.springframework.orm.ObjectOptimisticLockingFailureException; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + @Component public class ToscaResourceInstaller { - protected static final String NODES_VRF_ENTRY = "org.openecomp.nodes.VRFEntry"; - - protected static final String VLAN_NETWORK_RECEPTOR = "org.openecomp.nodes.VLANNetworkReceptor"; - - protected static final String ALLOTTED_RESOURCE = "Allotted Resource"; - - protected static final String MULTI_STAGE_DESIGN = "multi_stage_design"; - - protected static final String SCALABLE = "scalable"; - - protected static final String BASIC = "BASIC"; - - protected static final String PROVIDER = "PROVIDER"; - - protected static final String HEAT = "HEAT"; - - protected static final String MANUAL_RECORD = "MANUAL_RECORD"; - - protected static final String MSO = "SO"; - - protected static final String SDNC_MODEL_NAME = "sdnc_model_name"; - - protected static final String SDNC_MODEL_VERSION = "sdnc_model_version"; - - private static String CUSTOMIZATION_UUID = "customizationUUID"; - - - @Autowired - protected ServiceRepository serviceRepo; - - @Autowired - protected InstanceGroupRepository instanceGroupRepo; - - @Autowired - protected ServiceProxyResourceCustomizationRepository serviceProxyCustomizationRepo; - - @Autowired - protected CollectionResourceRepository collectionRepo; - - @Autowired - protected CollectionResourceCustomizationRepository collectionCustomizationRepo; - - @Autowired - protected ConfigurationResourceCustomizationRepository configCustomizationRepo; - - @Autowired - protected ConfigurationResourceRepository configRepo; - - @Autowired - protected VnfResourceRepository vnfRepo; - - @Autowired - protected VnfCustomizationRepository vnfCustomizationRepo; - - @Autowired - protected VFModuleRepository vfModuleRepo; - - @Autowired - protected VFModuleCustomizationRepository vfModuleCustomizationRepo; - - @Autowired - protected VnfcInstanceGroupCustomizationRepository vnfcInstanceGroupCustomizationRepo; - - @Autowired - protected VnfcCustomizationRepository vnfcCustomizationRepo; - - @Autowired - protected CvnfcCustomizationRepository cvnfcCustomizationRepo; - - @Autowired - protected AllottedResourceRepository allottedRepo; - - @Autowired - protected AllottedResourceCustomizationRepository allottedCustomizationRepo; - - @Autowired - protected NetworkResourceRepository networkRepo; - - @Autowired - protected HeatTemplateRepository heatRepo; - - @Autowired - protected NetworkResourceCustomizationRepository networkCustomizationRepo; + protected static final String NODES_VRF_ENTRY = "org.openecomp.nodes.VRFEntry"; + + protected static final String VLAN_NETWORK_RECEPTOR = "org.openecomp.nodes.VLANNetworkReceptor"; + + protected static final String ALLOTTED_RESOURCE = "Allotted Resource"; - @Autowired - protected WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository; - @Autowired - protected WatchdogDistributionStatusRepository watchdogDistributionStatusRepository; - @Autowired - protected WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository; - - @Autowired - protected TempNetworkHeatTemplateRepository tempNetworkLookupRepo; - - @Autowired - protected ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository; - - @Autowired - protected PnfResourceRepository pnfResourceRepository; - - @Autowired - protected PnfCustomizationRepository pnfCustomizationRepository; - - protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceInstaller.class); - - public boolean isResourceAlreadyDeployed(VfResourceStructure vfResourceStruct) throws ArtifactInstallerException { - boolean status = false; - VfResourceStructure vfResourceStructure = vfResourceStruct; - try { - status = vfResourceStructure.isDeployedSuccessfully(); - } catch (RuntimeException e) { - status = false; - } - try { - Service existingService = serviceRepo - .findOneByModelUUID(vfResourceStructure.getNotification().getServiceUUID()); - if (existingService != null) { - status = true; - } - if (status) { - logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(), - vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), - vfResourceStructure.getNotification().getServiceName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion()), - vfResourceStructure.getNotification().getServiceUUID(), - vfResourceStructure.getResourceInstance().getResourceName(), "", ""); - WatchdogComponentDistributionStatus wdStatus = new WatchdogComponentDistributionStatus( - vfResourceStruct.getNotification().getDistributionID(), MSO); - wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); - watchdogCDStatusRepository.saveAndFlush(wdStatus); - } else { - logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(), - vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), - vfResourceStructure.getNotification().getServiceName(), - BigDecimalVersion.castAndCheckNotificationVersionToString( - vfResourceStructure.getNotification().getServiceVersion()), - vfResourceStructure.getNotification().getServiceUUID(), - vfResourceStructure.getResourceInstance().getResourceName(), "", ""); - } - return status; - } catch (Exception e) { - logger - .error("{} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), - ErrorCode.SchemaError.getValue(), - "Exception - isResourceAlreadyDeployed"); - throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e); - } - } - - public void installTheComponentStatus(IStatusData iStatus) throws ArtifactInstallerException { - logger.debug("Entering installTheComponentStatus for distributionId {} and ComponentName {}", - iStatus.getDistributionID(), iStatus.getComponentName()); - - try { - WatchdogComponentDistributionStatus cdStatus = new WatchdogComponentDistributionStatus( - iStatus.getDistributionID(), - iStatus.getComponentName()); - cdStatus.setComponentDistributionStatus(iStatus.getStatus().toString()); - watchdogCDStatusRepository.save(cdStatus); - - } catch (Exception e) { - logger.debug("Exception caught in installTheComponentStatus {}", e.getMessage()); - throw new ArtifactInstallerException("Exception caught in installTheComponentStatus " + e.getMessage()); - } - } - - @Transactional(rollbackFor = {ArtifactInstallerException.class}) - public void installTheResource(ToscaResourceStructure toscaResourceStruct, ResourceStructure resourceStruct) - throws ArtifactInstallerException { - if (resourceStruct instanceof VfResourceStructure) { - installTheVfResouce(toscaResourceStruct, (VfResourceStructure) resourceStruct); - } else if (resourceStruct instanceof PnfResourceStructure) { - installPnfResource(toscaResourceStruct, (PnfResourceStructure) resourceStruct); - } else { - logger.warn("Unrecognized resource type"); - } - } - - private void installPnfResource(ToscaResourceStructure toscaResourceStruct, PnfResourceStructure resourceStruct) - throws ArtifactInstallerException { - - // PCLO: in case of deployment failure, use a string that will represent - // the type of artifact that failed... - List<ASDCElementInfo> artifactListForLogging = new ArrayList<>(); - try { - createToscaCsar(toscaResourceStruct); - Service service = createService(toscaResourceStruct, resourceStruct); - - processResourceSequence(toscaResourceStruct, service); - processPnfResources(toscaResourceStruct, service, resourceStruct); - serviceRepo.save(service); - - WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus( - resourceStruct.getNotification().getDistributionID(), MSO); - status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); - watchdogCDStatusRepository.save(status); - - toscaResourceStruct.setSuccessfulDeployment(); - - } catch (Exception e) { - logger.debug("Exception :", e); - WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus( - resourceStruct.getNotification().getDistributionID(), MSO); - status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name()); - watchdogCDStatusRepository.save(status); - Throwable dbExceptionToCapture = e; - while (!(dbExceptionToCapture instanceof ConstraintViolationException - || dbExceptionToCapture instanceof LockAcquisitionException) - && (dbExceptionToCapture.getCause() != null)) { - dbExceptionToCapture = dbExceptionToCapture.getCause(); - } - - if (dbExceptionToCapture instanceof ConstraintViolationException - || dbExceptionToCapture instanceof LockAcquisitionException) { - logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(), - resourceStruct.getResourceInstance().getResourceName(), - resourceStruct.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(), - "Exception - ASCDC Artifact already deployed", e); - } else { - String elementToLog = (!artifactListForLogging.isEmpty() - ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString() - : "No element listed"); - logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog, - ErrorCode.DataError.getValue(), - "Exception caught during installation of " + resourceStruct.getResourceInstance() - .getResourceName() - + ". Transaction rollback", e); - throw new ArtifactInstallerException("Exception caught during installation of " - + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback.", e); - } - } - } - - private void installTheVfResouce(ToscaResourceStructure toscaResourceStruct, VfResourceStructure resourceStruct) - throws ArtifactInstallerException { - VfResourceStructure vfResourceStructure = resourceStruct; - extractHeatInformation(toscaResourceStruct, vfResourceStructure); - - // PCLO: in case of deployment failure, use a string that will represent - // the type of artifact that failed... - List<ASDCElementInfo> artifactListForLogging = new ArrayList<>(); - try { - createToscaCsar(toscaResourceStruct); - Service service = createService(toscaResourceStruct, resourceStruct); - - processResourceSequence(toscaResourceStruct, service); - processVFResources(toscaResourceStruct, service, vfResourceStructure); - List<NodeTemplate> allottedResourceList = toscaResourceStruct.getSdcCsarHelper().getAllottedResources(); - processAllottedResources(toscaResourceStruct, service, allottedResourceList); - processNetworks(toscaResourceStruct, service); - // process Network Collections - processNetworkCollections(toscaResourceStruct, service); - // Process Service Proxy & Configuration - processServiceProxyAndConfiguration(toscaResourceStruct, service); - - serviceRepo.save(service); - - WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus( - resourceStruct.getNotification().getDistributionID(), MSO); - status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); - watchdogCDStatusRepository.save(status); - - toscaResourceStruct.setSuccessfulDeployment(); - - } catch (Exception e) { - logger.debug("Exception :", e); - WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus( - resourceStruct.getNotification().getDistributionID(), MSO); - status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name()); - watchdogCDStatusRepository.save(status); - Throwable dbExceptionToCapture = e; - while (!(dbExceptionToCapture instanceof ConstraintViolationException - || dbExceptionToCapture instanceof LockAcquisitionException) - && (dbExceptionToCapture.getCause() != null)) { - dbExceptionToCapture = dbExceptionToCapture.getCause(); - } - - if (dbExceptionToCapture instanceof ConstraintViolationException - || dbExceptionToCapture instanceof LockAcquisitionException) { - logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(), - vfResourceStructure.getResourceInstance().getResourceName(), - vfResourceStructure.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(), - "Exception - ASCDC Artifact already deployed", e); - } else { - String elementToLog = (!artifactListForLogging.isEmpty() - ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString() - : "No element listed"); - logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog, - ErrorCode.DataError.getValue(), - "Exception caught during installation of " + vfResourceStructure.getResourceInstance() - .getResourceName() - + ". Transaction rollback", e); - throw new ArtifactInstallerException("Exception caught during installation of " - + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback.", e); - } - } - } - - - List<NodeTemplate> getRequirementList(List<NodeTemplate> resultList, List<NodeTemplate> nodeTemplates, - ISdcCsarHelper iSdcCsarHelper) { - - List<NodeTemplate> nodes = new ArrayList<NodeTemplate>(); - nodes.addAll(nodeTemplates); - - for (NodeTemplate nodeTemplate : nodeTemplates) { - RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate); - List<RequirementAssignment> reqAs = requirement.getAll(); - for (RequirementAssignment ra : reqAs) { - String reqNode = ra.getNodeTemplateName(); - for (NodeTemplate rNode : resultList) { - if (rNode.getName().equals(reqNode)) { - if (!resultList.contains(nodeTemplate)) { - resultList.add(nodeTemplate); - } - if (nodes.contains(nodeTemplate)) { - nodes.remove(nodeTemplate); - } - break; - } - } - } - } - - if (!nodes.isEmpty()) { - getRequirementList(resultList, nodes, iSdcCsarHelper); - } - - return resultList; - } - - // This method retrieve resource sequence from csar file - void processResourceSequence(ToscaResourceStructure toscaResourceStructure, Service service) { - List<String> resouceSequence = new ArrayList<String>(); - List<NodeTemplate> resultList = new ArrayList<NodeTemplate>(); - - ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper(); - List<NodeTemplate> nodeTemplates = iSdcCsarHelper.getServiceNodeTemplates(); - List<NodeTemplate> nodes = new ArrayList<NodeTemplate>(); - nodes.addAll(nodeTemplates); - - for (NodeTemplate nodeTemplate : nodeTemplates) { - RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate); - - if (requirement == null || requirement.getAll() == null || requirement.getAll().isEmpty()) { - resultList.add(nodeTemplate); - nodes.remove(nodeTemplate); - } - } - - resultList = getRequirementList(resultList, nodes, iSdcCsarHelper); - - for (NodeTemplate node : resultList) { - String templateName = node.getMetaData().getValue("name"); - if (!resouceSequence.contains(templateName)) { - resouceSequence.add(templateName); - } - } - - String resourceSeqStr = resouceSequence.stream().collect(Collectors.joining(",")); - service.setResourceOrder(resourceSeqStr); - logger.debug(" resourceSeq for service uuid(" + service.getModelUUID() + ") : " + resourceSeqStr); - } - - private static String getValue(Object value, List<Input> servInputs) { - String output = null; - if (value instanceof Map) { - // currently this logic handles only one level of nesting. - return ((LinkedHashMap) value).values().toArray()[0].toString(); - } else if (value instanceof GetInput) { - String inputName = ((GetInput) value).getInputName(); - - for (Input input : servInputs) { - if (input.getName().equals(inputName)) { - // keep both input name and default value - // if service input does not supplies value the use default value - String defaultValue = input.getDefault() != null ? (String) input.getDefault().toString() : ""; - output = inputName + "|" + defaultValue;// return default value - } - } - - } else { - output = value != null ? value.toString() : ""; - } - return output; // return property value - } - - String getResourceInput(ToscaResourceStructure toscaResourceStructure, String resourceCustomizationUuid) - throws ArtifactInstallerException { - Map<String, String> resouceRequest = new HashMap<>(); - ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper(); - - List<Input> serInput = iSdcCsarHelper.getServiceInputs(); - Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream() - .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid)).findFirst(); - if (nodeTemplateOpt.isPresent()) { - NodeTemplate nodeTemplate = nodeTemplateOpt.get(); - LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties(); - - for (String key : resourceProperties.keySet()) { - Property property = resourceProperties.get(key); - - String value = getValue(property.getValue(), serInput); - resouceRequest.put(key, value); - } - } - - try { - ObjectMapper objectMapper = new ObjectMapper(); - String jsonStr = objectMapper.writeValueAsString(resouceRequest); - - jsonStr = jsonStr.replace("\"", "\\\""); - logger.debug( - "resource request for resource customization id (" + resourceCustomizationUuid + ") : " + jsonStr); - return jsonStr; - } catch (JsonProcessingException e) { - logger.error("resource input could not be deserialized for resource customization id (" - + resourceCustomizationUuid + ")"); - throw new ArtifactInstallerException("resource input could not be parsed", e); - } - } - - protected void processNetworks(ToscaResourceStructure toscaResourceStruct, - Service service) throws ArtifactInstallerException { - List<NodeTemplate> nodeTemplatesVLList = toscaResourceStruct.getSdcCsarHelper().getServiceVlList(); - - if (nodeTemplatesVLList != null) { - for (NodeTemplate vlNode : nodeTemplatesVLList) { - String networkResourceModelName = vlNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME); - - TempNetworkHeatTemplateLookup tempNetworkLookUp = - tempNetworkLookupRepo.findFirstBynetworkResourceModelName(networkResourceModelName); - - if (tempNetworkLookUp != null) { - HeatTemplate heatTemplate = - heatRepo.findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid()); - if (heatTemplate != null) { - NetworkResourceCustomization networkCustomization = - createNetwork(vlNode, - toscaResourceStruct, - heatTemplate, - tempNetworkLookUp.getAicVersionMax(), - tempNetworkLookUp.getAicVersionMin(), - service); - service.getNetworkCustomizations().add(networkCustomization); - } else { - throw new ArtifactInstallerException("No HeatTemplate found for artifactUUID: " - + tempNetworkLookUp.getHeatTemplateArtifactUuid()); - } - } else { - NetworkResourceCustomization networkCustomization = createNetwork(vlNode, - toscaResourceStruct, - null, - null, - null, - service); - service.getNetworkCustomizations().add(networkCustomization); - logger.debug("No NetworkResourceName found in TempNetworkHeatTemplateLookup for " - + networkResourceModelName); - } - - } - } - } - - protected void processAllottedResources(ToscaResourceStructure toscaResourceStruct, Service service, - List<NodeTemplate> allottedResourceList) { - if (allottedResourceList != null) { - for (NodeTemplate allottedNode : allottedResourceList) { - service.getAllottedCustomizations() - .add(createAllottedResource(allottedNode, toscaResourceStruct, service)); - } - } - } - - - protected ConfigurationResource getConfigurationResource(NodeTemplate nodeTemplate) { - Metadata metadata = nodeTemplate.getMetaData(); - ConfigurationResource configResource = new ConfigurationResource(); - configResource.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - configResource.setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - configResource.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - configResource.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - configResource.setDescription(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - configResource.setToscaNodeType(nodeTemplate.getType()); - return configResource; - } - - protected ConfigurationResourceCustomization getConfigurationResourceCustomization(NodeTemplate nodeTemplate, - ToscaResourceStructure toscaResourceStructure, - ServiceProxyResourceCustomization spResourceCustomization) { - Metadata metadata = nodeTemplate.getMetaData(); - - ConfigurationResource configResource = getConfigurationResource(nodeTemplate); - - ConfigurationResourceCustomization configCustomizationResource = new ConfigurationResourceCustomization(); - - Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>(); - - configCustomizationResource - .setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - configCustomizationResource.setModelInstanceName(nodeTemplate.getName()); - - configCustomizationResource.setNfFunction(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); - configCustomizationResource.setNfRole(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); - configCustomizationResource.setNfType(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); - configCustomizationResource - .setServiceProxyResourceCustomizationUUID(spResourceCustomization.getModelCustomizationUUID()); - - configCustomizationResource.setConfigurationResource(configResource); - configResourceCustomizationSet.add(configCustomizationResource); - - configResource.setConfigurationResourceCustomization(configResourceCustomizationSet); - return configCustomizationResource; - } - - - protected Optional<ConfigurationResourceCustomization> getVnrNodeTemplate( - List<NodeTemplate> configurationNodeTemplatesList, - ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization) { - Optional<ConfigurationResourceCustomization> configurationResourceCust = Optional.empty(); - for (NodeTemplate nodeTemplate : configurationNodeTemplatesList) { - StatefulEntityType entityType = nodeTemplate.getTypeDefinition(); - String type = entityType.getType(); - - if (VLAN_NETWORK_RECEPTOR.equals(type)) { - configurationResourceCust = Optional.of(getConfigurationResourceCustomization(nodeTemplate, - toscaResourceStructure, spResourceCustomization)); - break; - } - } - - return configurationResourceCust; - } - - protected void processServiceProxyAndConfiguration(ToscaResourceStructure toscaResourceStruct, Service service) { - - List<NodeTemplate> serviceProxyResourceList = toscaResourceStruct.getSdcCsarHelper() - .getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY); - - List<NodeTemplate> configurationNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper() - .getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION); - - List<ServiceProxyResourceCustomization> serviceProxyList = new ArrayList<ServiceProxyResourceCustomization>(); - List<ConfigurationResourceCustomization> configurationResourceList = new ArrayList<ConfigurationResourceCustomization>(); - - ServiceProxyResourceCustomization serviceProxy = null; - - if (serviceProxyResourceList != null) { - for (NodeTemplate spNode : serviceProxyResourceList) { - serviceProxy = createServiceProxy(spNode, service, toscaResourceStruct); - serviceProxyList.add(serviceProxy); - Optional<ConfigurationResourceCustomization> vnrResourceCustomization = getVnrNodeTemplate( - configurationNodeTemplatesList, toscaResourceStruct, serviceProxy); - - for (NodeTemplate configNode : configurationNodeTemplatesList) { - - List<RequirementAssignment> requirementsList = toscaResourceStruct.getSdcCsarHelper() - .getRequirementsOf(configNode).getAll(); - for (RequirementAssignment requirement : requirementsList) { - if (requirement.getNodeTemplateName().equals(spNode.getName())) { - ConfigurationResourceCustomization configurationResource = createConfiguration(configNode, - toscaResourceStruct, serviceProxy, vnrResourceCustomization); - - Optional<ConfigurationResourceCustomization> matchingObject = configurationResourceList - .stream() - .filter(configurationResourceCustomization -> configNode.getMetaData() - .getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID) - .equals(configurationResource.getModelCustomizationUUID())) - .findFirst(); - if (!matchingObject.isPresent()) { - configurationResourceList.add(configurationResource); - } - - break; - } - } - } - - } - } - - service.setConfigurationCustomizations(configurationResourceList); - service.setServiceProxyCustomizations(serviceProxyList); - } - - protected void processNetworkCollections(ToscaResourceStructure toscaResourceStruct, Service service) { - - List<NodeTemplate> networkCollectionList = toscaResourceStruct.getSdcCsarHelper() - .getServiceNodeTemplateBySdcType(SdcTypes.CR); - - if (networkCollectionList != null) { - for (NodeTemplate crNode : networkCollectionList) { - - createNetworkCollection(crNode, toscaResourceStruct, service); - collectionRepo.saveAndFlush(toscaResourceStruct.getCatalogCollectionResource()); - - List<NetworkInstanceGroup> networkInstanceGroupList = toscaResourceStruct - .getCatalogNetworkInstanceGroup(); - for (NetworkInstanceGroup networkInstanceGroup : networkInstanceGroupList) { - instanceGroupRepo.saveAndFlush(networkInstanceGroup); - } - - } - } - service.getCollectionResourceCustomizations() - .add(toscaResourceStruct.getCatalogCollectionResourceCustomization()); - } - - - protected void processVFResources(ToscaResourceStructure toscaResourceStruct, Service service, - VfResourceStructure vfResourceStructure) - throws Exception { - logger.debug("processVFResources"); - - List<NodeTemplate> vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList(); - - for (NodeTemplate nodeTemplate : vfNodeTemplatesList) { - Metadata metadata = nodeTemplate.getMetaData(); - String vfCustomizationCategory = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY); - logger.debug("VF Category is : " + vfCustomizationCategory); - - // Do not treat Allotted Resources as VNF resources - if (ALLOTTED_RESOURCE.equalsIgnoreCase(vfCustomizationCategory)) { - continue; - } - - String vfCustomizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); - logger.debug("VFCustomizationUUID=" + vfCustomizationUUID); - - IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance(); - - // Make sure the VF ResourceCustomizationUUID from the notification and tosca - // customizations match before comparing their VF Modules UUID's - logger.debug("Checking if Notification VF ResourceCustomizationUUID: " - + vfNotificationResource.getResourceCustomizationUUID() + " matches Tosca VF Customization UUID: " - + vfCustomizationUUID); - - if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) { - logger.debug("vfCustomizationUUID: " + vfCustomizationUUID - + " matches vfNotificationResource CustomizationUUID"); - - processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata, - vfCustomizationCategory); - } else { - logger.debug("Notification VF ResourceCustomizationUUID: " - + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match " - + "Tosca VF Customization UUID: " + vfCustomizationUUID); - } - } - } - - /** - * This is used to process the PNF specific resource, including resource and resource_customization. {@link - * IEntityDetails} based API is used to retrieve information. Please check {@link ISdcCsarHelper} for details. - */ - protected void processPnfResources(ToscaResourceStructure toscaResourceStruct, Service service, - PnfResourceStructure resourceStructure) throws Exception { - logger.info("Processing PNF resource: {}", resourceStructure.getResourceInstance().getResourceUUID()); - - ISdcCsarHelper sdcCsarHelper = toscaResourceStruct.getSdcCsarHelper(); - EntityQuery entityQuery = EntityQuery.newBuilder(SdcTypes.PNF).build(); - TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build(); - - List<IEntityDetails> entityDetailsList = sdcCsarHelper.getEntity(entityQuery, topologyTemplateQuery, false); - for (IEntityDetails entityDetails : entityDetailsList) { - Metadata metadata = entityDetails.getMetadata(); - String customizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); - String modelUuid = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID); - String notifCustomizationUUID = resourceStructure.getResourceInstance().getResourceCustomizationUUID(); - if (customizationUUID != null && customizationUUID.equals(notifCustomizationUUID)) { - logger.info("Resource customization UUID: {} is the same as notified resource customizationUUID: {}", - customizationUUID, notifCustomizationUUID); - - if (checkExistingPnfResourceCutomization(customizationUUID)) { - logger.info("Resource customization UUID: {} already deployed", customizationUUID); - } else { - PnfResource pnfResource = findExistingPnfResource(service, modelUuid); - if (pnfResource == null) { - pnfResource = createPnfResource(entityDetails); - } - PnfResourceCustomization pnfResourceCustomization = createPnfResourceCustomization(entityDetails, - pnfResource); - pnfResource.getPnfResourceCustomizations().add(pnfResourceCustomization); - toscaResourceStruct.setPnfResourceCustomization(pnfResourceCustomization); - service.getPnfCustomizations().add(pnfResourceCustomization); - } - } else { - logger - .warn("Resource customization UUID: {} is NOT the same as notified resource customizationUUID: {}", - customizationUUID, notifCustomizationUUID); - } - } - } - - private PnfResource findExistingPnfResource(Service service, String modelUuid) { - PnfResource pnfResource = null; - for (PnfResourceCustomization pnfResourceCustomization : service.getPnfCustomizations()) { - if (pnfResourceCustomization.getPnfResources() != null && pnfResourceCustomization.getPnfResources() - .getModelUUID().equals(modelUuid)) { - pnfResource = pnfResourceCustomization.getPnfResources(); - } - } - if (pnfResource == null) { - pnfResource = pnfResourceRepository.findById(modelUuid).orElse(pnfResource); - } - return pnfResource; - } - - private boolean checkExistingPnfResourceCutomization(String customizationUUID) { - return pnfCustomizationRepository.findById(customizationUUID).isPresent(); - } - - /** - * Construct the {@link PnfResource} from {@link IEntityDetails} object. - */ - private PnfResource createPnfResource(IEntityDetails entity) { - PnfResource pnfResource = new PnfResource(); - Metadata metadata = entity.getMetadata(); - pnfResource.setModelInvariantUUID( - testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - pnfResource.setModelName(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - pnfResource.setModelUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - pnfResource.setModelVersion( - testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - pnfResource.setDescription( - testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - pnfResource.setCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY))); - pnfResource.setSubCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY))); - pnfResource.setToscaNodeType(entity.getToscaType()); - return pnfResource; - } - - /** - * Construct the {@link PnfResourceCustomization} from {@link IEntityDetails} object. - */ - private PnfResourceCustomization createPnfResourceCustomization(IEntityDetails entityDetails, - PnfResource pnfResource) { - - PnfResourceCustomization pnfResourceCustomization = new PnfResourceCustomization(); - Metadata metadata = entityDetails.getMetadata(); - Map<String, Property> properties = entityDetails.getProperties(); - pnfResourceCustomization - .setModelCustomizationUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - pnfResourceCustomization.setModelInstanceName(entityDetails.getName()); - pnfResourceCustomization - .setNfFunction(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); - pnfResourceCustomization.setNfNamingCode(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFCODE))); - pnfResourceCustomization.setNfRole(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFROLE))); - pnfResourceCustomization.setNfType(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFTYPE))); - pnfResourceCustomization.setMultiStageDesign(getStringValue(properties.get(MULTI_STAGE_DESIGN))); - pnfResourceCustomization.setBlueprintName(getStringValue(properties.get(SDNC_MODEL_NAME))); - pnfResourceCustomization.setBlueprintVersion(getStringValue(properties.get(SDNC_MODEL_VERSION))); - - pnfResourceCustomization.setPnfResources(pnfResource); - - return pnfResourceCustomization; - } - - /** - * Get value from {@link Property} and cast to String value. Return empty String if property is null value. - */ - private String getStringValue(Property property) { - if (null == property) { - return ""; - } - Object value = property.getValue(); - return String.valueOf(value); - } - - protected void processVfModules(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStructure, - Service service, NodeTemplate nodeTemplate, Metadata metadata, String vfCustomizationCategory) - throws Exception { - - logger.debug("VF Category is : " + vfCustomizationCategory); - - VnfResourceCustomization vnfResource = createVnfResource(nodeTemplate, toscaResourceStruct, service); - - if (vfResourceStructure.getVfModuleStructure() != null && !vfResourceStructure.getVfModuleStructure() - .isEmpty()) { - - String vfCustomizationUUID = toscaResourceStruct.getSdcCsarHelper() - .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); - logger.debug("VFCustomizationUUID=" + vfCustomizationUUID); - - IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance(); - - // Make sure the VF ResourceCustomizationUUID from the notification and tosca customizations match before comparing their VF Modules UUID's - logger.debug("Checking if Notification VF ResourceCustomizationUUID: " + vfNotificationResource - .getResourceCustomizationUUID() + - " matches Tosca VF Customization UUID: " + vfCustomizationUUID); - - if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) { - - logger.debug("vfCustomizationUUID: " + vfCustomizationUUID - + " matches vfNotificationResource CustomizationUUID"); - - Set<CvnfcCustomization> existingCvnfcSet = new HashSet<CvnfcCustomization>(); - Set<VnfcCustomization> existingVnfcSet = new HashSet<VnfcCustomization>(); - - for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) { - - logger.debug("vfModuleStructure:" + vfModuleStructure.toString()); - List<org.onap.sdc.toscaparser.api.Group> vfGroups = toscaResourceStruct - .getSdcCsarHelper().getVfModulesByVf(vfCustomizationUUID); - IVfModuleData vfMetadata = vfModuleStructure.getVfModuleMetadata(); - - logger.debug("Comparing Vf_Modules_Metadata CustomizationUUID : " + vfMetadata - .getVfModuleModelCustomizationUUID()); - - Optional<org.onap.sdc.toscaparser.api.Group> matchingObject = vfGroups.stream() - .peek(group -> logger.debug( - "To Csar Group VFModuleModelCustomizationUUID " + group.getMetadata() - .getValue("vfModuleModelCustomizationUUID"))) - .filter(group -> group.getMetadata().getValue("vfModuleModelCustomizationUUID") - .equals(vfMetadata.getVfModuleModelCustomizationUUID())) - .findFirst(); - if (matchingObject.isPresent()) { - VfModuleCustomization vfModuleCustomization = createVFModuleResource(matchingObject.get(), - nodeTemplate, toscaResourceStruct, - vfResourceStructure, vfMetadata, vnfResource, service, existingCvnfcSet, existingVnfcSet); - vfModuleCustomization.getVfModule().setVnfResources(vnfResource.getVnfResources()); - } else { - throw new Exception( - "Cannot find matching VFModule Customization in Csar for Vf_Modules_Metadata: " + vfMetadata - .getVfModuleModelCustomizationUUID()); - } - - } - - } else { - logger.debug("Notification VF ResourceCustomizationUUID: " + vfNotificationResource - .getResourceCustomizationUUID() + " doesn't match " + - "Tosca VF Customization UUID: " + vfCustomizationUUID); - } - } - - service.getVnfCustomizations().add(vnfResource); - } - - public void processWatchdog(String distributionId, String servideUUID, Optional<String> distributionNotification, - String consumerId) { - WatchdogServiceModVerIdLookup modVerIdLookup = new WatchdogServiceModVerIdLookup(distributionId, servideUUID, - distributionNotification, consumerId); - watchdogModVerIdLookupRepository.saveAndFlush(modVerIdLookup); - - try { - - WatchdogDistributionStatus distributionStatus = new WatchdogDistributionStatus(distributionId); - watchdogDistributionStatusRepository.saveAndFlush(distributionStatus); - - } catch (ObjectOptimisticLockingFailureException e) { - logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : " + e.toString()); - throw e; - } - } - - protected void extractHeatInformation(ToscaResourceStructure toscaResourceStruct, - VfResourceStructure vfResourceStructure) { - for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { - - switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) { - case ASDCConfiguration.HEAT: - case ASDCConfiguration.HEAT_NESTED: - createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, - vfModuleArtifact); - break; - case ASDCConfiguration.HEAT_VOL: - createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, - vfModuleArtifact); - VfModuleArtifact envModuleArtifact = getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, - vfModuleArtifact); - createHeatEnvFromArtifact(vfResourceStructure, envModuleArtifact); - break; - case ASDCConfiguration.HEAT_ENV: - createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact); - break; - case ASDCConfiguration.HEAT_ARTIFACT: - createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact, - toscaResourceStruct); - break; - case ASDCConfiguration.HEAT_NET: - case ASDCConfiguration.OTHER: - logger.warn("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT.toString(), - vfModuleArtifact.getArtifactInfo().getArtifactType() + "(Artifact Name:" + vfModuleArtifact - .getArtifactInfo() - .getArtifactName() + ")", ErrorCode.DataError.getValue(), - "Artifact type not supported"); - break; - default: - break; - - } - } - } - - protected VfModuleArtifact getHeatEnvArtifactFromGeneratedArtifact(VfResourceStructure vfResourceStructure, - VfModuleArtifact vfModuleArtifact) { - String artifactName = vfModuleArtifact.getArtifactInfo().getArtifactName(); - artifactName = artifactName.substring(0, artifactName.indexOf('.')); - for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { - if (moduleArtifact.getArtifactInfo().getArtifactName().contains(artifactName) - && moduleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) { - return moduleArtifact; - } - } - return null; - } - - public String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure, - List<String> listTypes) { - String newFileBody = filebody; - for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { - - if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) { - - newFileBody = verifyTheFilePrefixInString(newFileBody, - moduleArtifact.getArtifactInfo().getArtifactName()); - } - } - return newFileBody; - } - - public String verifyTheFilePrefixInString(final String body, final String filenameToVerify) { - - String needlePrefix = "file:///"; - String prefixedFilenameToVerify = needlePrefix + filenameToVerify; - - if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) { - return body; - } - - StringBuilder sb = new StringBuilder(body.length()); - - int currentIndex = 0; - int startIndex = 0; - - while (currentIndex != -1) { - startIndex = currentIndex; - currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex); - - if (currentIndex == -1) { - break; - } - // We append from the startIndex up to currentIndex (start of File - // Name) - sb.append(body.substring(startIndex, currentIndex)); - sb.append(filenameToVerify); - - currentIndex += prefixedFilenameToVerify.length(); - } - - sb.append(body.substring(startIndex)); - - return sb.toString(); - } - - protected void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure, - ToscaResourceStructure toscaResourceStruct, VfModuleArtifact vfModuleArtifact) { - HeatTemplate heatTemplate = new HeatTemplate(); - List<String> typeList = new ArrayList<>(); - typeList.add(ASDCConfiguration.HEAT_NESTED); - typeList.add(ASDCConfiguration.HEAT_ARTIFACT); - - heatTemplate.setTemplateBody( - verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); - heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - - if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) { - heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout()); - } else { - heatTemplate.setTimeoutMinutes(240); - } - - heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatTemplate.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { - heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatTemplate.setArtifactChecksum(MANUAL_RECORD); - } - - Set<HeatTemplateParam> heatParam = extractHeatTemplateParameters( - vfModuleArtifact.getResult(), vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatTemplate.setParameters(heatParam); - vfModuleArtifact.setHeatTemplate(heatTemplate); - } - - protected void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure, - VfModuleArtifact vfModuleArtifact) { - HeatEnvironment heatEnvironment = new HeatEnvironment(); - heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - List<String> typeList = new ArrayList<>(); - typeList.add(ASDCConfiguration.HEAT); - typeList.add(ASDCConfiguration.HEAT_VOL); - heatEnvironment.setEnvironment( - verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); - heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatEnvironment.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - - if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { - heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatEnvironment.setArtifactChecksum(MANUAL_RECORD); - } - vfModuleArtifact.setHeatEnvironment(heatEnvironment); - } - - protected void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure, - VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) { - - HeatFiles heatFile = new HeatFiles(); - heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); - heatFile.setFileBody(vfModuleArtifact.getResult()); - heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName()); - heatFile.setVersion(BigDecimalVersion - .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); - toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); - if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { - heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); - } else { - heatFile.setArtifactChecksum(MANUAL_RECORD); - } - vfModuleArtifact.setHeatFiles(heatFile); - } - - protected Service createService(ToscaResourceStructure toscaResourceStructure, - ResourceStructure resourceStructure) { - - Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata(); - - Service service = new Service(); - - if (serviceMetadata != null) { - - if (toscaResourceStructure.getServiceVersion() != null) { - service.setModelVersion(toscaResourceStructure.getServiceVersion()); - } - - service.setServiceType(serviceMetadata.getValue("serviceType")); - service.setServiceRole(serviceMetadata.getValue("serviceRole")); - service.setCategory(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)); - service.setDescription(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - service.setModelName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - service.setModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - service.setEnvironmentContext(serviceMetadata.getValue("environmentContext")); - - if (resourceStructure != null) { - service.setWorkloadContext(resourceStructure.getNotification().getWorkloadContext()); - } - - service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - service.setCsar(toscaResourceStructure.getCatalogToscaCsar()); - } - - toscaResourceStructure.setCatalogService(service); - return service; - } - - protected ServiceProxyResourceCustomization createServiceProxy(NodeTemplate nodeTemplate, Service service, - ToscaResourceStructure toscaResourceStructure) { - - Metadata spMetadata = nodeTemplate.getMetaData(); - - ServiceProxyResourceCustomization spCustomizationResource = new ServiceProxyResourceCustomization(); - - Set<ServiceProxyResourceCustomization> serviceProxyCustomizationSet = new HashSet<>(); - - spCustomizationResource.setModelName(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - spCustomizationResource - .setModelInvariantUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - spCustomizationResource.setModelUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - spCustomizationResource.setModelVersion(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - spCustomizationResource.setDescription(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - - spCustomizationResource - .setModelCustomizationUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - spCustomizationResource.setModelInstanceName(nodeTemplate.getName()); - spCustomizationResource.setToscaNodeType(nodeTemplate.getType()); - - String sourceServiceUUID = spMetadata.getValue("sourceModelUuid"); - - Service sourceService = serviceRepo.findOneByModelUUID(sourceServiceUUID); - - spCustomizationResource.setSourceService(sourceService); - spCustomizationResource.setToscaNodeType(nodeTemplate.getType()); - serviceProxyCustomizationSet.add(spCustomizationResource); - - toscaResourceStructure.setCatalogServiceProxyResourceCustomization(spCustomizationResource); - - return spCustomizationResource; - } - - protected ConfigurationResourceCustomization createConfiguration(NodeTemplate nodeTemplate, - ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization, - Optional<ConfigurationResourceCustomization> vnrResourceCustomization) { - - ConfigurationResourceCustomization configCustomizationResource = getConfigurationResourceCustomization( - nodeTemplate, - toscaResourceStructure, spResourceCustomization); - - ConfigurationResource configResource = getConfigurationResource(nodeTemplate); - - Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>(); - - StatefulEntityType entityType = nodeTemplate.getTypeDefinition(); - String type = entityType.getType(); - - if (NODES_VRF_ENTRY.equals(type)) { - configCustomizationResource.setConfigResourceCustomization(vnrResourceCustomization.orElse(null)); - } - - configCustomizationResource.setConfigurationResource(configResource); - - configResourceCustomizationSet.add(configCustomizationResource); - - configResource.setConfigurationResourceCustomization(configResourceCustomizationSet); - - toscaResourceStructure.setCatalogConfigurationResource(configResource); - - toscaResourceStructure.setCatalogConfigurationResourceCustomization(configCustomizationResource); - - return configCustomizationResource; - } - - protected ConfigurationResource createFabricConfiguration(NodeTemplate nodeTemplate, - ToscaResourceStructure toscaResourceStructure) { - - Metadata fabricMetadata = nodeTemplate.getMetaData(); - - ConfigurationResource configResource = new ConfigurationResource(); - - configResource.setModelName(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - configResource.setModelInvariantUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - configResource.setModelUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - configResource.setModelVersion(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - configResource.setDescription(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - configResource.setToscaNodeType(nodeTemplate.getType()); - - return configResource; - } - - protected void createToscaCsar(ToscaResourceStructure toscaResourceStructure) { - ToscaCsar toscaCsar = new ToscaCsar(); - if (toscaResourceStructure.getToscaArtifact().getArtifactChecksum() != null) { - toscaCsar.setArtifactChecksum(toscaResourceStructure.getToscaArtifact().getArtifactChecksum()); - } else { - toscaCsar.setArtifactChecksum(MANUAL_RECORD); - } - toscaCsar.setArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID()); - toscaCsar.setName(toscaResourceStructure.getToscaArtifact().getArtifactName()); - toscaCsar.setVersion(toscaResourceStructure.getToscaArtifact().getArtifactVersion()); - toscaCsar.setDescription(toscaResourceStructure.getToscaArtifact().getArtifactDescription()); - toscaCsar.setUrl(toscaResourceStructure.getToscaArtifact().getArtifactURL()); - - toscaResourceStructure.setCatalogToscaCsar(toscaCsar); - } - - protected VnfcCustomization findExistingVfc(Set<VnfcCustomization> vnfcCustomizations, String customizationUUID) { - VnfcCustomization vnfcCustomization = null; - for (VnfcCustomization vnfcCustom : vnfcCustomizations) { - if (vnfcCustom != null && vnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) { - vnfcCustomization = vnfcCustom; - } - } - - if (vnfcCustomization == null) { - vnfcCustomization = vnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID); - } - - return vnfcCustomization; - } - - protected CvnfcCustomization findExistingCvfc(Set<CvnfcCustomization> cvnfcCustomizations, - String customizationUUID) { - CvnfcCustomization cvnfcCustomization = null; - for (CvnfcCustomization cvnfcCustom : cvnfcCustomizations) { - if (cvnfcCustom != null && cvnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) { - cvnfcCustomization = cvnfcCustom; - } - } - - if (cvnfcCustomization == null) { - cvnfcCustomization = cvnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID); - } - - return cvnfcCustomization; - } - - protected NetworkResourceCustomization createNetwork(NodeTemplate networkNodeTemplate, - ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin, - Service service) { - - NetworkResourceCustomization networkResourceCustomization = networkCustomizationRepo - .findOneByModelCustomizationUUID( - networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - - boolean networkUUIDsMatch = true; - // Check to make sure the NetworkResourceUUID on the Customization record matches the NetworkResourceUUID from the distribution. - // If not we'll update the Customization record with latest from the distribution - if (networkResourceCustomization != null) { - String existingNetworkModelUUID = networkResourceCustomization.getNetworkResource().getModelUUID(); - String latestNetworkModelUUID = networkNodeTemplate.getMetaData() - .getValue(SdcPropertyNames.PROPERTY_NAME_UUID); - - if (!existingNetworkModelUUID.equals(latestNetworkModelUUID)) { - networkUUIDsMatch = false; - } - - } - - if (networkResourceCustomization != null && !networkUUIDsMatch) { - - NetworkResource networkResource = createNetworkResource(networkNodeTemplate, toscaResourceStructure, - heatTemplate, - aicMax, aicMin); - - networkResourceCustomization.setNetworkResource(networkResource); - - networkCustomizationRepo.saveAndFlush(networkResourceCustomization); - - } else if (networkResourceCustomization == null) { - networkResourceCustomization = createNetworkResourceCustomization(networkNodeTemplate, - toscaResourceStructure); - - NetworkResource networkResource = findExistingNetworkResource(service, - networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - if (networkResource == null) { - networkResource = createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate, - aicMax, aicMin); - } - - networkResource.addNetworkResourceCustomization(networkResourceCustomization); - networkResourceCustomization.setNetworkResource(networkResource); - } - - return networkResourceCustomization; - } - - protected NetworkResource findExistingNetworkResource(Service service, String modelUUID) { - NetworkResource networkResource = null; - for (NetworkResourceCustomization networkCustom : service.getNetworkCustomizations()) { - if (networkCustom.getNetworkResource() != null - && networkCustom.getNetworkResource().getModelUUID().equals(modelUUID)) { - networkResource = networkCustom.getNetworkResource(); - } - } - if (networkResource == null) { - networkResource = networkRepo.findResourceByModelUUID(modelUUID); - } - - return networkResource; - } - - protected NetworkResourceCustomization createNetworkResourceCustomization(NodeTemplate networkNodeTemplate, - ToscaResourceStructure toscaResourceStructure) { - NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization(); - networkResourceCustomization.setModelInstanceName( - testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - networkResourceCustomization.setModelCustomizationUUID( - testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - - networkResourceCustomization.setNetworkTechnology( - testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, - SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY))); - networkResourceCustomization.setNetworkType(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE))); - networkResourceCustomization.setNetworkRole(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE))); - networkResourceCustomization.setNetworkScope(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE))); - return networkResourceCustomization; - } - - protected NetworkResource createNetworkResource(NodeTemplate networkNodeTemplate, - ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin) { - NetworkResource networkResource = new NetworkResource(); - String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue( - networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK); - - if ("true".equalsIgnoreCase(providerNetwork)) { - networkResource.setNeutronNetworkType(PROVIDER); - } else { - networkResource.setNeutronNetworkType(BASIC); - } - - networkResource.setModelName( - testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - - networkResource.setModelInvariantUUID( - testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - networkResource.setModelUUID( - testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - networkResource.setModelVersion( - testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - - networkResource.setAicVersionMax(aicMax); - networkResource.setAicVersionMin(aicMin); - networkResource.setToscaNodeType(networkNodeTemplate.getType()); - networkResource.setDescription( - testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - networkResource.setOrchestrationMode(HEAT); - networkResource.setHeatTemplate(heatTemplate); - return networkResource; - } - - protected CollectionNetworkResourceCustomization createNetworkCollection(NodeTemplate networkNodeTemplate, - ToscaResourceStructure toscaResourceStructure, Service service) { - - CollectionNetworkResourceCustomization collectionNetworkResourceCustomization = new CollectionNetworkResourceCustomization(); - - // **** Build Object to populate Collection_Resource table - CollectionResource collectionResource = new CollectionResource(); - - collectionResource - .setModelName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - collectionResource.setModelInvariantUUID( - networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - collectionResource - .setModelUUID(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - collectionResource - .setModelVersion(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - collectionResource - .setDescription(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - collectionResource.setToscaNodeType(networkNodeTemplate.getType()); - - toscaResourceStructure.setCatalogCollectionResource(collectionResource); - - // **** Build object to populate Collection_Resource_Customization table - NetworkCollectionResourceCustomization ncfc = new NetworkCollectionResourceCustomization(); - - ncfc.setFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, - "cr_function")); - ncfc.setRole(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, - "cr_role")); - ncfc.setType(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, - "cr_type")); - - ncfc.setModelInstanceName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - ncfc.setModelCustomizationUUID( - networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - - Set<CollectionNetworkResourceCustomization> networkResourceCustomizationSet = new HashSet<>(); - networkResourceCustomizationSet.add(collectionNetworkResourceCustomization); - - ncfc.setNetworkResourceCustomization(networkResourceCustomizationSet); - - ncfc.setCollectionResource(collectionResource); - toscaResourceStructure.setCatalogCollectionResourceCustomization(ncfc); - - //*** Build object to populate the Instance_Group table - List<Group> groupList = toscaResourceStructure.getSdcCsarHelper() - .getGroupsOfOriginOfNodeTemplateByToscaGroupType(networkNodeTemplate, - "org.openecomp.groups.NetworkCollection"); - - List<NetworkInstanceGroup> networkInstanceGroupList = new ArrayList<>(); - - List<CollectionResourceInstanceGroupCustomization> collectionResourceInstanceGroupCustomizationList = new ArrayList<CollectionResourceInstanceGroupCustomization>(); - - for (Group group : groupList) { - - NetworkInstanceGroup networkInstanceGroup = new NetworkInstanceGroup(); - Metadata instanceMetadata = group.getMetadata(); - networkInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - networkInstanceGroup - .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - networkInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - networkInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - networkInstanceGroup.setToscaNodeType(group.getType()); - networkInstanceGroup.setRole(SubType.SUB_INTERFACE.toString()); // Set - // Role - networkInstanceGroup.setType(InstanceGroupType.L3_NETWORK); // Set - // type - networkInstanceGroup.setCollectionResource(collectionResource); - - // ****Build object to populate - // Collection_Resource_Instance_Group_Customization table - CollectionResourceInstanceGroupCustomization crInstanceGroupCustomization = new CollectionResourceInstanceGroupCustomization(); - crInstanceGroupCustomization.setInstanceGroup(networkInstanceGroup); - crInstanceGroupCustomization.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - crInstanceGroupCustomization.setModelCustomizationUUID( - networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - - // Loop through the template policy to find the subinterface_network_quantity property name. Then extract the value for it. - List<Policy> policyList = toscaResourceStructure.getSdcCsarHelper() - .getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(networkNodeTemplate, - "org.openecomp.policies.scaling.Fixed"); - - if (policyList != null) { - for (Policy policy : policyList) { - for (String policyNetworkCollection : policy.getTargets()) { - - if (policyNetworkCollection.equalsIgnoreCase(group.getName())) { - - Map<String, Object> propMap = policy.getPolicyProperties(); - - if (propMap.get("quantity") != null) { - - String quantity = toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(networkNodeTemplate, - getPropertyInput(propMap.get("quantity").toString())); - - if (quantity != null) { - crInstanceGroupCustomization - .setSubInterfaceNetworkQuantity(Integer.parseInt(quantity)); - } - - } - - } - } - } - } - - crInstanceGroupCustomization.setDescription( - toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, - instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME) - + "_network_collection_description")); - crInstanceGroupCustomization.setFunction( - toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, - instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME) - + "_network_collection_function")); - crInstanceGroupCustomization.setCollectionResourceCust(ncfc); - collectionResourceInstanceGroupCustomizationList.add(crInstanceGroupCustomization); - - networkInstanceGroup - .setCollectionInstanceGroupCustomizations(collectionResourceInstanceGroupCustomizationList); - - networkInstanceGroupList.add(networkInstanceGroup); - - toscaResourceStructure.setCatalogNetworkInstanceGroup(networkInstanceGroupList); - - List<NodeTemplate> vlNodeList = toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplateBySdcType(networkNodeTemplate, SdcTypes.VL); - - List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizationList = new ArrayList<>(); - - //*****Build object to populate the NetworkResource table - NetworkResource networkResource = new NetworkResource(); - - for (NodeTemplate vlNodeTemplate : vlNodeList) { - - String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue( - vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK); - - if ("true".equalsIgnoreCase(providerNetwork)) { - networkResource.setNeutronNetworkType(PROVIDER); - } else { - networkResource.setNeutronNetworkType(BASIC); - } - - networkResource - .setModelName(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - - networkResource.setModelInvariantUUID( - vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - networkResource - .setModelUUID(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - networkResource - .setModelVersion(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - - networkResource.setAicVersionMax( - vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)); - - TempNetworkHeatTemplateLookup tempNetworkLookUp = tempNetworkLookupRepo - .findFirstBynetworkResourceModelName( - vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - - if (tempNetworkLookUp != null) { - - HeatTemplate heatTemplate = heatRepo - .findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid()); - networkResource.setHeatTemplate(heatTemplate); - - networkResource.setAicVersionMin(tempNetworkLookUp.getAicVersionMin()); - - } - - networkResource.setToscaNodeType(vlNodeTemplate.getType()); - networkResource - .setDescription(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - networkResource.setOrchestrationMode(HEAT); - - // Build object to populate the - // Collection_Network_Resource_Customization table - for (NodeTemplate memberNode : group.getMemberNodes()) { - collectionNetworkResourceCustomization.setModelInstanceName(memberNode.getName()); - } - - collectionNetworkResourceCustomization.setModelCustomizationUUID( - vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - - collectionNetworkResourceCustomization.setNetworkTechnology( - toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNodeTemplate, - SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY)); - collectionNetworkResourceCustomization.setNetworkType(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE)); - collectionNetworkResourceCustomization.setNetworkRole(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)); - collectionNetworkResourceCustomization.setNetworkScope(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE)); - collectionNetworkResourceCustomization.setInstanceGroup(networkInstanceGroup); - collectionNetworkResourceCustomization.setNetworkResource(networkResource); - collectionNetworkResourceCustomization.setNetworkResourceCustomization(ncfc); - - collectionNetworkResourceCustomizationList.add(collectionNetworkResourceCustomization); - } - - } - - return collectionNetworkResourceCustomization; - } - - protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(NodeTemplate vnfcNodeTemplate, Group group, - VnfResourceCustomization vnfResourceCustomization, ToscaResourceStructure toscaResourceStructure) { - - Metadata instanceMetadata = group.getMetadata(); - // Populate InstanceGroup - VFCInstanceGroup vfcInstanceGroup = new VFCInstanceGroup(); - - vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - vfcInstanceGroup.setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); - vfcInstanceGroup.setToscaNodeType(group.getType()); - vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role - vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type - - //Populate VNFCInstanceGroupCustomization - VnfcInstanceGroupCustomization vfcInstanceGroupCustom = new VnfcInstanceGroupCustomization(); - - vfcInstanceGroupCustom.setModelCustomizationUUID(vnfResourceCustomization.getModelCustomizationUUID()); - vfcInstanceGroupCustom.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - - String getInputName = null; - String groupProperty = toscaResourceStructure.getSdcCsarHelper() - .getGroupPropertyLeafValue(group, "vfc_instance_group_function"); - if (groupProperty != null) { - int getInputIndex = groupProperty.indexOf("{get_input="); - if (getInputIndex > -1) { - getInputName = groupProperty.substring(getInputIndex + 11, groupProperty.length() - 1); - } - } - vfcInstanceGroupCustom.setFunction( - toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vnfcNodeTemplate, getInputName)); - - vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup); - vfcInstanceGroupCustom.setVnfResourceCust(vnfResourceCustomization); - - return vfcInstanceGroupCustom; - - } - - protected VfModuleCustomization createVFModuleResource(Group group, NodeTemplate vfTemplate, - ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure, - IVfModuleData vfModuleData, VnfResourceCustomization vnfResource, Service service, - Set<CvnfcCustomization> existingCvnfcSet, Set<VnfcCustomization> existingVnfcSet) { - - VfModuleCustomization vfModuleCustomization = findExistingVfModuleCustomization(vnfResource, - vfModuleData.getVfModuleModelCustomizationUUID()); - if (vfModuleCustomization == null) { - VfModule vfModule = findExistingVfModule(vnfResource, - vfTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); - Metadata vfMetadata = group.getMetadata(); - if (vfModule == null) { - vfModule = createVfModule(group, toscaResourceStructure, vfModuleData, vfMetadata); - } - - vfModuleCustomization = createVfModuleCustomization(group, toscaResourceStructure, vfModule, vfModuleData); - setHeatInformationForVfModule(toscaResourceStructure, vfResourceStructure, vfModule, vfModuleCustomization, - vfMetadata); - vfModuleCustomization.setVfModule(vfModule); - vfModule.getVfModuleCustomization().add(vfModuleCustomization); - vnfResource.getVfModuleCustomizations().add(vfModuleCustomization); - } else { - vfResourceStructure.setAlreadyDeployed(true); - } - - //****************************************************************************************************************** - //* Extract VFC's and CVFC's then add them to VFModule - //****************************************************************************************************************** - - Set<VnfVfmoduleCvnfcConfigurationCustomization> vnfVfmoduleCvnfcConfigurationCustomizations = new HashSet<VnfVfmoduleCvnfcConfigurationCustomization>(); - Set<CvnfcCustomization> cvnfcCustomizations = new HashSet<CvnfcCustomization>(); - Set<VnfcCustomization> vnfcCustomizations = new HashSet<VnfcCustomization>(); - - // Only set the CVNFC if this vfModule group is a member of it. - List<NodeTemplate> groupMembers = toscaResourceStructure.getSdcCsarHelper() - .getMembersOfVfModule(vfTemplate, group); - String vfModuleMemberName = null; - - for (NodeTemplate node : groupMembers) { - vfModuleMemberName = node.getName(); - } - - // Extract CVFC lists - List<NodeTemplate> cvfcList = toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplateBySdcType(vfTemplate, SdcTypes.CVFC); - - for (NodeTemplate cvfcTemplate : cvfcList) { - - CvnfcCustomization existingCvnfcCustomization = findExistingCvfc(existingCvnfcSet, - cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - - if (vfModuleMemberName != null && vfModuleMemberName.equalsIgnoreCase(cvfcTemplate.getName())) { - - //Extract associated VFC - Should always be just one - List<NodeTemplate> vfcList = toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplateBySdcType(cvfcTemplate, SdcTypes.VFC); - - for (NodeTemplate vfcTemplate : vfcList) { - - VnfcCustomization vnfcCustomization = new VnfcCustomization(); - VnfcCustomization existingVnfcCustomization = null; - - existingVnfcCustomization = findExistingVfc(existingVnfcSet, - vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - - if (existingVnfcCustomization == null) { - vnfcCustomization = new VnfcCustomization(); - } else { - vnfcCustomization = existingVnfcCustomization; - } - - // Only Add Abstract VNFC's to our DB, ignore all others - if (existingVnfcCustomization == null && vfcTemplate.getMetaData() - .getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY).equalsIgnoreCase("Abstract")) { - vnfcCustomization.setModelCustomizationUUID( - vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - vnfcCustomization.setModelInstanceName(vfcTemplate.getName()); - vnfcCustomization.setModelInvariantUUID( - vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - vnfcCustomization - .setModelName(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - vnfcCustomization - .setModelUUID(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - - vnfcCustomization.setModelVersion( - testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - vnfcCustomization.setDescription( - testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - vnfcCustomization.setToscaNodeType(testNull(vfcTemplate.getType())); - - vnfcCustomizations.add(vnfcCustomization); - existingVnfcSet.add(vnfcCustomization); - } - - // This check is needed incase the VFC subcategory is something other than Abstract. In that case we want to skip adding that record to our DB. - if (vnfcCustomization.getModelCustomizationUUID() != null) { - - CvnfcCustomization cvnfcCustomization = null; - - if (existingCvnfcCustomization != null) { - cvnfcCustomization = existingCvnfcCustomization; - } else { - - cvnfcCustomization = new CvnfcCustomization(); - cvnfcCustomization.setModelCustomizationUUID( - cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - cvnfcCustomization.setModelInstanceName(cvfcTemplate.getName()); - cvnfcCustomization.setModelInvariantUUID( - cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); - cvnfcCustomization - .setModelName(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); - cvnfcCustomization - .setModelUUID(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - - cvnfcCustomization.setModelVersion( - testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - cvnfcCustomization.setDescription( - testNull( - cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - cvnfcCustomization.setToscaNodeType(testNull(cvfcTemplate.getType())); - - if (existingVnfcCustomization != null) { - cvnfcCustomization.setVnfcCustomization(existingVnfcCustomization); - } else { - cvnfcCustomization.setVnfcCustomization(vnfcCustomization); - } - - cvnfcCustomization.setNfcFunction(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_function")); - cvnfcCustomization.setNfcNamingCode(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_naming_code")); - cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization); - cvnfcCustomization.setVnfResourceCustomization(vnfResource); - - cvnfcCustomizations.add(cvnfcCustomization); - existingCvnfcSet.add(cvnfcCustomization); - } - - //***************************************************************************************************************************************** - //* Extract Fabric Configuration - //***************************************************************************************************************************************** - - List<NodeTemplate> fabricConfigList = toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplateBySdcType(vfTemplate, SdcTypes.CONFIGURATION); - - for (NodeTemplate fabricTemplate : fabricConfigList) { - - ConfigurationResource fabricConfig = null; - - ConfigurationResource existingConfig = findExistingConfiguration(service, - fabricTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - - if (existingConfig == null) { - - fabricConfig = createFabricConfiguration(fabricTemplate, toscaResourceStructure); - - } else { - fabricConfig = existingConfig; - } - - VnfVfmoduleCvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = createVfCnvfConfigCustomization( - fabricTemplate, toscaResourceStructure, - vnfResource, vfModuleCustomization, cvnfcCustomization, fabricConfig, vfTemplate, - vfModuleMemberName); - - vnfVfmoduleCvnfcConfigurationCustomizations.add(vnfVfmoduleCvnfcConfigurationCustomization); - } - - } - - } - - } - - } - - vfModuleCustomization.setCvnfcCustomization(cvnfcCustomizations); - vfModuleCustomization - .setVnfVfmoduleCvnfcConfigurationCustomization(vnfVfmoduleCvnfcConfigurationCustomizations); - - return vfModuleCustomization; - } - - protected VnfVfmoduleCvnfcConfigurationCustomization createVfCnvfConfigCustomization(NodeTemplate fabricTemplate, - ToscaResourceStructure toscaResourceStruct, - VnfResourceCustomization vnfResource, VfModuleCustomization vfModuleCustomization, - CvnfcCustomization cvnfcCustomization, - ConfigurationResource configResource, NodeTemplate vfTemplate, String vfModuleMemberName) { - - Metadata fabricMetadata = fabricTemplate.getMetaData(); - - VnfVfmoduleCvnfcConfigurationCustomization vfModuleToCvnfc = new VnfVfmoduleCvnfcConfigurationCustomization(); - - vfModuleToCvnfc.setConfigurationResource(configResource); - vfModuleToCvnfc.setCvnfcCustomization(cvnfcCustomization); - vfModuleToCvnfc - .setModelCustomizationUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - vfModuleToCvnfc.setModelInstanceName(fabricTemplate.getName()); - vfModuleToCvnfc.setVfModuleCustomization(vfModuleCustomization); - vfModuleToCvnfc.setVnfResourceCustomization(vnfResource); - - List<Policy> policyList = toscaResourceStruct.getSdcCsarHelper() - .getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(vfTemplate, "org.openecomp.policies.External"); - - if (policyList != null) { - for (Policy policy : policyList) { - - for (String policyCvfcTarget : policy.getTargets()) { - - if (policyCvfcTarget.equalsIgnoreCase(vfModuleMemberName)) { - - Map<String, Object> propMap = policy.getPolicyProperties(); - - if (propMap.get("type").toString().equalsIgnoreCase("Fabric Policy")) { - vfModuleToCvnfc.setPolicyName(propMap.get("name").toString()); - } - } - } - } - } - - vfModuleToCvnfc.setConfigurationFunction( - toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "function")); - vfModuleToCvnfc.setConfigurationRole( - toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "role")); - vfModuleToCvnfc.setConfigurationType( - toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "type")); - - return vfModuleToCvnfc; - } - - protected ConfigurationResource findExistingConfiguration(Service service, String modelUUID) { - ConfigurationResource configResource = null; - for (ConfigurationResourceCustomization configurationResourceCustom : service - .getConfigurationCustomizations()) { - if (configurationResourceCustom.getConfigurationResource() != null - && configurationResourceCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) { - configResource = configurationResourceCustom.getConfigurationResource(); - } - } - if (configResource == null) { - configResource = configRepo.findResourceByModelUUID(modelUUID); - } - - return configResource; - } - - protected VfModuleCustomization findExistingVfModuleCustomization(VnfResourceCustomization vnfResource, - String vfModuleModelCustomizationUUID) { - VfModuleCustomization vfModuleCustomization = null; - for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) { - if (vfModuleCustom.getModelCustomizationUUID().equalsIgnoreCase(vfModuleModelCustomizationUUID)) { - vfModuleCustomization = vfModuleCustom; - } - } - if (vfModuleCustomization == null) { - vfModuleCustomization = vfModuleCustomizationRepo - .findByModelCustomizationUUID(vfModuleModelCustomizationUUID); - } - - return vfModuleCustomization; - } - - protected VfModule findExistingVfModule(VnfResourceCustomization vnfResource, String modelUUID) { - VfModule vfModule = null; - for (VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()) { - if (vfModuleCustom.getVfModule() != null && vfModuleCustom.getVfModule().getModelUUID().equals(modelUUID)) { - vfModule = vfModuleCustom.getVfModule(); - } - } - if (vfModule == null) { - vfModule = vfModuleRepo.findByModelUUID(modelUUID); - } - - return vfModule; - } - - protected VfModuleCustomization createVfModuleCustomization(Group group, - ToscaResourceStructure toscaResourceStructure, VfModule vfModule, IVfModuleData vfModuleData) { - VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); - - vfModuleCustomization.setModelCustomizationUUID(vfModuleData.getVfModuleModelCustomizationUUID()); - - vfModuleCustomization.setVfModule(vfModule); - - String initialCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, - SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT); - if (initialCount != null && initialCount.length() > 0) { - vfModuleCustomization.setInitialCount(Integer.valueOf(initialCount)); - } - - vfModuleCustomization.setInitialCount(Integer.valueOf(toscaResourceStructure.getSdcCsarHelper() - .getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT))); - - String availabilityZoneCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, - SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT); - if (availabilityZoneCount != null && availabilityZoneCount.length() > 0) { - vfModuleCustomization.setAvailabilityZoneCount(Integer.valueOf(availabilityZoneCount)); - } - - vfModuleCustomization.setLabel(toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, - SdcPropertyNames.PROPERTY_NAME_VFMODULELABEL)); - - String maxInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, - SdcPropertyNames.PROPERTY_NAME_MAXVFMODULEINSTANCES); - if (maxInstances != null && maxInstances.length() > 0) { - vfModuleCustomization.setMaxInstances(Integer.valueOf(maxInstances)); - } - - String minInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, - SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES); - if (minInstances != null && minInstances.length() > 0) { - vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances)); - } - return vfModuleCustomization; - } - - protected VfModule createVfModule(Group group, ToscaResourceStructure toscaResourceStructure, - IVfModuleData vfModuleData, Metadata vfMetadata) { - VfModule vfModule = new VfModule(); - String vfModuleModelUUID = vfModuleData.getVfModuleModelUUID(); - - if (vfModuleModelUUID == null) { - vfModuleModelUUID = testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, - SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); - } else if (vfModuleModelUUID.indexOf('.') > -1) { - vfModuleModelUUID = vfModuleModelUUID.substring(0, vfModuleModelUUID.indexOf('.')); - } - - vfModule.setModelInvariantUUID(testNull(toscaResourceStructure.getSdcCsarHelper() - .getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID))); - vfModule.setModelName(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, - SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME))); - vfModule.setModelUUID(vfModuleModelUUID); - vfModule.setModelVersion(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, - SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION))); - vfModule.setDescription(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, - SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - - String vfModuleType = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, - SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE); - if (vfModuleType != null && "Base".equalsIgnoreCase(vfModuleType)) { - vfModule.setIsBase(true); - } else { - vfModule.setIsBase(false); - } - return vfModule; - } - - protected void setHeatInformationForVfModule(ToscaResourceStructure toscaResourceStructure, - VfResourceStructure vfResourceStructure, VfModule vfModule, VfModuleCustomization vfModuleCustomization, - Metadata vfMetadata) { - - Optional<VfModuleStructure> matchingObject = vfResourceStructure.getVfModuleStructure().stream() - .filter(vfModuleStruct -> vfModuleStruct.getVfModuleMetadata().getVfModuleModelUUID() - .equalsIgnoreCase(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, - SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID))) - .findFirst(); - - if (matchingObject.isPresent()) { - List<HeatFiles> heatFilesList = new ArrayList<>(); - List<HeatTemplate> volumeHeatChildTemplates = new ArrayList<HeatTemplate>(); - List<HeatTemplate> heatChildTemplates = new ArrayList<HeatTemplate>(); - HeatTemplate parentHeatTemplate = new HeatTemplate(); - String parentArtifactType = null; - Set<String> artifacts = new HashSet<>(matchingObject.get().getVfModuleMetadata().getArtifacts()); - for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { - - List<HeatTemplate> childNestedHeatTemplates = new ArrayList<HeatTemplate>(); - - if (artifacts.contains(vfModuleArtifact.getArtifactInfo().getArtifactUUID())) { - checkVfModuleArtifactType(vfModule, vfModuleCustomization, heatFilesList, vfModuleArtifact, - childNestedHeatTemplates, parentHeatTemplate, vfResourceStructure); - } - - if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) { - parentArtifactType = identifyParentOfNestedTemplate(matchingObject.get(), vfModuleArtifact); - - if (!childNestedHeatTemplates.isEmpty()) { - - if (parentArtifactType != null && parentArtifactType - .equalsIgnoreCase(ASDCConfiguration.HEAT_VOL)) { - volumeHeatChildTemplates.add(childNestedHeatTemplates.get(0)); - } else { - heatChildTemplates.add(childNestedHeatTemplates.get(0)); - } - } - } - - } - if (!heatFilesList.isEmpty()) { - vfModule.setHeatFiles(heatFilesList); - } - - // Set all Child Templates related to HEAT_VOLUME - if (!volumeHeatChildTemplates.isEmpty()) { - if (vfModule.getVolumeHeatTemplate() != null) { - vfModule.getVolumeHeatTemplate().setChildTemplates(volumeHeatChildTemplates); - } else { - logger.debug("VolumeHeatTemplate not set in setHeatInformationForVfModule()"); - } - } - - // Set all Child Templates related to HEAT - if (!heatChildTemplates.isEmpty()) { - if (vfModule.getModuleHeatTemplate() != null) { - vfModule.getModuleHeatTemplate().setChildTemplates(heatChildTemplates); - } else { - logger.debug("ModuleHeatTemplate not set in setHeatInformationForVfModule()"); - } - } - } - } - - protected void checkVfModuleArtifactType(VfModule vfModule, VfModuleCustomization vfModuleCustomization, - List<HeatFiles> heatFilesList, VfModuleArtifact vfModuleArtifact, List<HeatTemplate> nestedHeatTemplates, - HeatTemplate parentHeatTemplate, VfResourceStructure vfResourceStructure) { - if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT)) { - vfModuleArtifact.incrementDeployedInDB(); - vfModule.setModuleHeatTemplate(vfModuleArtifact.getHeatTemplate()); - } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_VOL)) { - vfModule.setVolumeHeatTemplate(vfModuleArtifact.getHeatTemplate()); - VfModuleArtifact volVfModuleArtifact = this - .getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact); - vfModuleCustomization.setVolumeHeatEnv(volVfModuleArtifact.getHeatEnvironment()); - vfModuleArtifact.incrementDeployedInDB(); - } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) { - if (vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) { - vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment()); - } else { - vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment()); - } - vfModuleArtifact.incrementDeployedInDB(); - } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)) { - heatFilesList.add(vfModuleArtifact.getHeatFiles()); - vfModuleArtifact.incrementDeployedInDB(); - } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) { - nestedHeatTemplates.add(vfModuleArtifact.getHeatTemplate()); - vfModuleArtifact.incrementDeployedInDB(); - } - } - - protected VnfResourceCustomization createVnfResource(NodeTemplate vfNodeTemplate, - ToscaResourceStructure toscaResourceStructure, Service service) { - VnfResourceCustomization vnfResourceCustomization = vnfCustomizationRepo.findOneByModelCustomizationUUID( - vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - if (vnfResourceCustomization == null) { - VnfResource vnfResource = findExistingVnfResource(service, - vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - - if (vnfResource == null) { - vnfResource = createVnfResource(vfNodeTemplate); - } - - vnfResourceCustomization = createVnfResourceCustomization(vfNodeTemplate, toscaResourceStructure, - vnfResource); - vnfResourceCustomization.setVnfResources(vnfResource); - vnfResource.getVnfResourceCustomizations().add(vnfResourceCustomization); - - // Fetch VNFC Instance Group Info - List<Group> groupList = toscaResourceStructure.getSdcCsarHelper() - .getGroupsOfOriginOfNodeTemplateByToscaGroupType(vfNodeTemplate, - "org.openecomp.groups.VfcInstanceGroup"); - - for (Group group : groupList) { - - VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization = createVNFCInstanceGroup(vfNodeTemplate, - group, vnfResourceCustomization, toscaResourceStructure); - - vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization); - } - } - return vnfResourceCustomization; - } - - protected VnfResource findExistingVnfResource(Service service, String modelUUID) { - VnfResource vnfResource = null; - for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) { - if (vnfResourceCustom.getVnfResources() != null - && vnfResourceCustom.getVnfResources().getModelUUID().equals(modelUUID)) { - vnfResource = vnfResourceCustom.getVnfResources(); - } - } - if (vnfResource == null) { - vnfResource = vnfRepo.findResourceByModelUUID(modelUUID); - } - - return vnfResource; - } - - protected VnfResourceCustomization createVnfResourceCustomization(NodeTemplate vfNodeTemplate, - ToscaResourceStructure toscaResourceStructure, VnfResource vnfResource) { - VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization(); - vnfResourceCustomization.setModelCustomizationUUID( - testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - vnfResourceCustomization.setModelInstanceName(vfNodeTemplate.getName()); - - vnfResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); - vnfResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfNodeTemplate, "nf_naming_code"))); - vnfResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE))); - vnfResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE))); - - vnfResourceCustomization.setMultiStageDesign(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfNodeTemplate, MULTI_STAGE_DESIGN)); - - vnfResourceCustomization.setBlueprintName(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_NAME))); - - vnfResourceCustomization.setBlueprintVersion(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_VERSION))); - - vnfResourceCustomization.setVnfResources(vnfResource); - vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger( - vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT))); - - CapabilityAssignments vnfCustomizationCapability = toscaResourceStructure.getSdcCsarHelper() - .getCapabilitiesOf(vfNodeTemplate); - - if (vnfCustomizationCapability != null) { - CapabilityAssignment capAssign = vnfCustomizationCapability.getCapabilityByName(SCALABLE); - - if (capAssign != null) { - vnfResourceCustomization.setMinInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper() - .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); - vnfResourceCustomization.setMaxInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper() - .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); - } - - } - - toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization); - - return vnfResourceCustomization; - } - - protected VnfResource createVnfResource(NodeTemplate vfNodeTemplate) { - VnfResource vnfResource = new VnfResource(); - vnfResource.setModelInvariantUUID( - testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - vnfResource.setModelName(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - vnfResource.setModelUUID(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - - vnfResource.setModelVersion( - testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - vnfResource.setDescription( - testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); - vnfResource.setOrchestrationMode(HEAT); - vnfResource.setToscaNodeType(testNull(vfNodeTemplate.getType())); - vnfResource.setAicVersionMax( - testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); - vnfResource.setAicVersionMin( - testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); - vnfResource.setCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)); - vnfResource.setSubCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)); - - return vnfResource; - } - - protected AllottedResourceCustomization createAllottedResource(NodeTemplate nodeTemplate, - ToscaResourceStructure toscaResourceStructure, Service service) { - AllottedResourceCustomization allottedResourceCustomization = allottedCustomizationRepo - .findOneByModelCustomizationUUID( - nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); - - if (allottedResourceCustomization == null) { - AllottedResource allottedResource = findExistingAllottedResource(service, - nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); - - if (allottedResource == null) { - allottedResource = createAR(nodeTemplate); - } - - toscaResourceStructure.setAllottedResource(allottedResource); - allottedResourceCustomization = createAllottedResourceCustomization(nodeTemplate, toscaResourceStructure); - allottedResourceCustomization.setAllottedResource(allottedResource); - allottedResource.getAllotedResourceCustomization().add(allottedResourceCustomization); - } - return allottedResourceCustomization; - } - - protected AllottedResource findExistingAllottedResource(Service service, String modelUUID) { - AllottedResource allottedResource = null; - for (AllottedResourceCustomization allottedResourceCustom : service.getAllottedCustomizations()) { - if (allottedResourceCustom.getAllottedResource() != null - && allottedResourceCustom.getAllottedResource().getModelUUID().equals(modelUUID)) { - allottedResource = allottedResourceCustom.getAllottedResource(); - } - } - if (allottedResource == null) { - allottedResource = allottedRepo.findResourceByModelUUID(modelUUID); - } - - return allottedResource; - } - - protected AllottedResourceCustomization createAllottedResourceCustomization(NodeTemplate nodeTemplate, - ToscaResourceStructure toscaResourceStructure) { - AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization(); - allottedResourceCustomization.setModelCustomizationUUID( - testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); - allottedResourceCustomization.setModelInstanceName(nodeTemplate.getName()); - - allottedResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); - allottedResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, "nf_naming_code"))); - allottedResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE))); - allottedResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE))); - - List<NodeTemplate> vfcNodes = toscaResourceStructure.getSdcCsarHelper() - .getVfcListByVf(allottedResourceCustomization.getModelCustomizationUUID()); - - if (vfcNodes != null) { - for (NodeTemplate vfcNode : vfcNodes) { - - allottedResourceCustomization.setProvidingServiceModelUUID(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_uuid")); - allottedResourceCustomization.setProvidingServiceModelInvariantUUID( - toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_invariant_uuid")); - allottedResourceCustomization.setProvidingServiceModelName(toscaResourceStructure.getSdcCsarHelper() - .getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_name")); - } - } - - CapabilityAssignments arCustomizationCapability = toscaResourceStructure.getSdcCsarHelper() - .getCapabilitiesOf(nodeTemplate); - - if (arCustomizationCapability != null) { - CapabilityAssignment capAssign = arCustomizationCapability.getCapabilityByName(SCALABLE); - - if (capAssign != null) { - allottedResourceCustomization.setMinInstances( - Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue( - capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); - allottedResourceCustomization.setMaxInstances( - Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue( - capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); - } - } - return allottedResourceCustomization; - } - - protected AllottedResource createAR(NodeTemplate nodeTemplate) { - AllottedResource allottedResource = new AllottedResource(); - allottedResource - .setModelUUID(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); - allottedResource.setModelInvariantUUID( - testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); - allottedResource - .setModelName(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); - allottedResource - .setModelVersion(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); - allottedResource.setToscaNodeType(testNull(nodeTemplate.getType())); - allottedResource.setSubcategory( - testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY))); - allottedResource - .setDescription(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); - return allottedResource; - } - - protected Set<HeatTemplateParam> extractHeatTemplateParameters(String yamlFile, String artifactUUID) { - // Scan the payload downloadResult and extract the HeatTemplate - // parameters - YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes()); - return yamlEditor.getParameterList(artifactUUID); - } - - protected String testNull(Object object) { - - if (object == null) { - return null; - } else if (object.equals("NULL")) { - return null; - } else if (object instanceof Integer) { - return object.toString(); - } else if (object instanceof String) { - return (String) object; - } else { - return "Type not recognized"; - } - } - - protected static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure, - VfModuleArtifact heatNestedArtifact) { - - if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null && vfModuleStructure - .getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) { - for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0) - .getArtifactInfo().getRelatedArtifacts()) { - if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { - return ASDCConfiguration.HEAT; - } - - } - } - - if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null - && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo() - .getRelatedArtifacts() != null) { - for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) - .get(0).getArtifactInfo().getRelatedArtifacts()) { - if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { - return ASDCConfiguration.HEAT_VOL; - } - - } - } - - // Does not belong to anything - return null; - - } - - protected static String createVNFName(VfResourceStructure vfResourceStructure) { - - return vfResourceStructure.getNotification().getServiceName() + "/" - + vfResourceStructure.getResourceInstance().getResourceInstanceName(); - } - - protected static String createVfModuleName(VfModuleStructure vfModuleStructure) { - - return createVNFName(vfModuleStructure.getParentVfResource()) + "::" - + vfModuleStructure.getVfModuleMetadata().getVfModuleModelName(); - } - - protected String getPropertyInput(String propertyName) { - - String inputName = new String(); - - if (propertyName != null) { - int getInputIndex = propertyName.indexOf("{get_input="); - if (getInputIndex > -1) { - inputName = propertyName.substring(getInputIndex + 11, propertyName.length() - 1); - } - } - - return inputName; - } - - - protected static Timestamp getCurrentTimeStamp() { - - return new Timestamp(new Date().getTime()); - } + protected static final String MULTI_STAGE_DESIGN = "multi_stage_design"; + + protected static final String SCALABLE = "scalable"; + + protected static final String BASIC = "BASIC"; + + protected static final String PROVIDER = "PROVIDER"; + + protected static final String HEAT = "HEAT"; + + protected static final String MANUAL_RECORD = "MANUAL_RECORD"; + + protected static final String MSO = "SO"; + + protected static final String SDNC_MODEL_NAME = "sdnc_model_name"; + + protected static final String SDNC_MODEL_VERSION = "sdnc_model_version"; + + private static String CUSTOMIZATION_UUID = "customizationUUID"; + + + @Autowired + protected ServiceRepository serviceRepo; + + @Autowired + protected InstanceGroupRepository instanceGroupRepo; + + @Autowired + protected ServiceProxyResourceCustomizationRepository serviceProxyCustomizationRepo; + + @Autowired + protected CollectionResourceRepository collectionRepo; + + @Autowired + protected CollectionResourceCustomizationRepository collectionCustomizationRepo; + + @Autowired + protected ConfigurationResourceCustomizationRepository configCustomizationRepo; + + @Autowired + protected ConfigurationResourceRepository configRepo; + + @Autowired + protected VnfResourceRepository vnfRepo; + + @Autowired + protected VnfCustomizationRepository vnfCustomizationRepo; + + @Autowired + protected VFModuleRepository vfModuleRepo; + + @Autowired + protected VFModuleCustomizationRepository vfModuleCustomizationRepo; + + @Autowired + protected VnfcInstanceGroupCustomizationRepository vnfcInstanceGroupCustomizationRepo; + + @Autowired + protected VnfcCustomizationRepository vnfcCustomizationRepo; + + @Autowired + protected CvnfcCustomizationRepository cvnfcCustomizationRepo; + + @Autowired + protected AllottedResourceRepository allottedRepo; + + @Autowired + protected AllottedResourceCustomizationRepository allottedCustomizationRepo; + + @Autowired + protected NetworkResourceRepository networkRepo; + + @Autowired + protected HeatTemplateRepository heatRepo; + + @Autowired + protected NetworkResourceCustomizationRepository networkCustomizationRepo; + + @Autowired + protected WatchdogComponentDistributionStatusRepository watchdogCDStatusRepository; + @Autowired + protected WatchdogDistributionStatusRepository watchdogDistributionStatusRepository; + @Autowired + protected WatchdogServiceModVerIdLookupRepository watchdogModVerIdLookupRepository; + + @Autowired + protected TempNetworkHeatTemplateRepository tempNetworkLookupRepo; + + @Autowired + protected ExternalServiceToInternalServiceRepository externalServiceToInternalServiceRepository; + + @Autowired + protected PnfResourceRepository pnfResourceRepository; + + @Autowired + protected PnfCustomizationRepository pnfCustomizationRepository; + + protected static final Logger logger = LoggerFactory.getLogger(ToscaResourceInstaller.class); + + public boolean isResourceAlreadyDeployed(VfResourceStructure vfResourceStruct) throws ArtifactInstallerException { + boolean status = false; + VfResourceStructure vfResourceStructure = vfResourceStruct; + try { + status = vfResourceStructure.isDeployedSuccessfully(); + } catch (RuntimeException e) { + status = false; + } + try { + Service existingService = serviceRepo.findOneByModelUUID(vfResourceStructure.getNotification().getServiceUUID()); + if(existingService != null) + status = true; + if (status) { + logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(), + vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), + vfResourceStructure.getNotification().getServiceName(), + BigDecimalVersion.castAndCheckNotificationVersionToString( + vfResourceStructure.getNotification().getServiceVersion()), + vfResourceStructure.getNotification().getServiceUUID(), + vfResourceStructure.getResourceInstance().getResourceName(), "", ""); + WatchdogComponentDistributionStatus wdStatus = new WatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), MSO); + wdStatus.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); + watchdogCDStatusRepository.saveAndFlush(wdStatus); + } else { + logger.info(vfResourceStructure.getResourceInstance().getResourceInstanceName(), + vfResourceStructure.getResourceInstance().getResourceCustomizationUUID(), + vfResourceStructure.getNotification().getServiceName(), + BigDecimalVersion.castAndCheckNotificationVersionToString( + vfResourceStructure.getNotification().getServiceVersion()), + vfResourceStructure.getNotification().getServiceUUID(), + vfResourceStructure.getResourceInstance().getResourceName(), "", ""); + } + return status; + } catch (Exception e) { + logger + .error("{} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), ErrorCode.SchemaError.getValue(), + "Exception - isResourceAlreadyDeployed"); + throw new ArtifactInstallerException("Exception caught during checking existence of the VNF Resource.", e); + } + } + + public void installTheComponentStatus(IStatusData iStatus) throws ArtifactInstallerException { + logger.debug("Entering installTheComponentStatus for distributionId {} and ComponentName {}", + iStatus.getDistributionID(), iStatus.getComponentName()); + + try { + WatchdogComponentDistributionStatus cdStatus = new WatchdogComponentDistributionStatus(iStatus.getDistributionID(), + iStatus.getComponentName()); + cdStatus.setComponentDistributionStatus(iStatus.getStatus().toString()); + watchdogCDStatusRepository.save(cdStatus); + + } catch (Exception e) { + logger.debug("Exception caught in installTheComponentStatus {}", e.getMessage()); + throw new ArtifactInstallerException("Exception caught in installTheComponentStatus " + e.getMessage()); + } + } + + @Transactional(rollbackFor = {ArtifactInstallerException.class}) + public void installTheResource(ToscaResourceStructure toscaResourceStruct, ResourceStructure resourceStruct) + throws ArtifactInstallerException { + if (resourceStruct instanceof VfResourceStructure) { + installTheVfResource(toscaResourceStruct, (VfResourceStructure) resourceStruct); + } else if (resourceStruct instanceof PnfResourceStructure) { + installPnfResource(toscaResourceStruct, (PnfResourceStructure) resourceStruct); + } else { + logger.warn("Unrecognized resource type"); + } + } + + private void installPnfResource(ToscaResourceStructure toscaResourceStruct, PnfResourceStructure resourceStruct) + throws ArtifactInstallerException { + + // PCLO: in case of deployment failure, use a string that will represent + // the type of artifact that failed... + List<ASDCElementInfo> artifactListForLogging = new ArrayList<>(); + try { + createToscaCsar(toscaResourceStruct); + Service service = createService(toscaResourceStruct, resourceStruct); + + processResourceSequence(toscaResourceStruct, service); + processPnfResources(toscaResourceStruct, service, resourceStruct); + serviceRepo.save(service); + + WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus( + resourceStruct.getNotification().getDistributionID(), MSO); + status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); + watchdogCDStatusRepository.save(status); + + toscaResourceStruct.setSuccessfulDeployment(); + + } catch (Exception e) { + logger.debug("Exception :", e); + WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus( + resourceStruct.getNotification().getDistributionID(), MSO); + status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name()); + watchdogCDStatusRepository.save(status); + Throwable dbExceptionToCapture = e; + while (!(dbExceptionToCapture instanceof ConstraintViolationException + || dbExceptionToCapture instanceof LockAcquisitionException) + && (dbExceptionToCapture.getCause() != null)) { + dbExceptionToCapture = dbExceptionToCapture.getCause(); + } + + if (dbExceptionToCapture instanceof ConstraintViolationException + || dbExceptionToCapture instanceof LockAcquisitionException) { + logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(), + resourceStruct.getResourceInstance().getResourceName(), + resourceStruct.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(), + "Exception - ASCDC Artifact already deployed", e); + } else { + String elementToLog = (!artifactListForLogging.isEmpty() + ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString() + : "No element listed"); + logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog, + ErrorCode.DataError.getValue(), + "Exception caught during installation of " + resourceStruct.getResourceInstance() + .getResourceName() + + ". Transaction rollback", e); + throw new ArtifactInstallerException("Exception caught during installation of " + + resourceStruct.getResourceInstance().getResourceName() + ". Transaction rollback.", e); + } + } + } + @Transactional(rollbackFor = { ArtifactInstallerException.class }) + public void installTheVfResource(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStruct) + throws ArtifactInstallerException { + VfResourceStructure vfResourceStructure = vfResourceStruct; + extractHeatInformation(toscaResourceStruct, vfResourceStructure); + + // PCLO: in case of deployment failure, use a string that will represent + // the type of artifact that failed... + List<ASDCElementInfo> artifactListForLogging = new ArrayList<>(); + try { + createToscaCsar(toscaResourceStruct); + Service service = createService(toscaResourceStruct, vfResourceStruct); + List<NodeTemplate> vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList(); + + + for (NodeTemplate nodeTemplate : vfNodeTemplatesList) { + + Metadata metadata = nodeTemplate.getMetaData(); + String serviceType = toscaResourceStruct.getCatalogService().getServiceType(); + String vfCustomizationCategory = toscaResourceStruct.getSdcCsarHelper() + .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CATEGORY); + processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata, + vfCustomizationCategory); + } + + processResourceSequence(toscaResourceStruct, service); + processVFResources(toscaResourceStruct, service, vfResourceStructure); + List<NodeTemplate> allottedResourceList = toscaResourceStruct.getSdcCsarHelper().getAllottedResources(); + processAllottedResources(toscaResourceStruct, service, allottedResourceList); + processNetworks(toscaResourceStruct, service); + // process Network Collections + processNetworkCollections(toscaResourceStruct, service); + // Process Service Proxy & Configuration + processServiceProxyAndConfiguration(toscaResourceStruct, service); + + serviceRepo.save(service); + + WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), MSO); + status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_OK.name()); + watchdogCDStatusRepository.save(status); + + toscaResourceStruct.setSuccessfulDeployment(); + + } catch (Exception e) { + logger.debug("Exception :", e); + WatchdogComponentDistributionStatus status = new WatchdogComponentDistributionStatus(vfResourceStruct.getNotification().getDistributionID(), MSO); + status.setComponentDistributionStatus(DistributionStatusEnum.COMPONENT_DONE_ERROR.name()); + watchdogCDStatusRepository.save(status); + Throwable dbExceptionToCapture = e; + while (!(dbExceptionToCapture instanceof ConstraintViolationException + || dbExceptionToCapture instanceof LockAcquisitionException) + && (dbExceptionToCapture.getCause() != null)) { + dbExceptionToCapture = dbExceptionToCapture.getCause(); + } + + if (dbExceptionToCapture instanceof ConstraintViolationException + || dbExceptionToCapture instanceof LockAcquisitionException) { + logger.warn("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_ALREADY_DEPLOYED.toString(), + vfResourceStructure.getResourceInstance().getResourceName(), + vfResourceStructure.getNotification().getServiceVersion(), ErrorCode.DataError.getValue(), + "Exception - ASCDC Artifact already deployed", e); + } else { + String elementToLog = (!artifactListForLogging.isEmpty() + ? artifactListForLogging.get(artifactListForLogging.size() - 1).toString() + : "No element listed"); + logger.error("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_INSTALL_EXC.toString(), elementToLog, + ErrorCode.DataError.getValue(), + "Exception caught during installation of " + vfResourceStructure.getResourceInstance().getResourceName() + + ". Transaction rollback", e); + throw new ArtifactInstallerException("Exception caught during installation of " + + vfResourceStructure.getResourceInstance().getResourceName() + ". Transaction rollback.", e); + } + } + } + + + List<NodeTemplate> getRequirementList(List<NodeTemplate> resultList, List<NodeTemplate> nodeTemplates, + ISdcCsarHelper iSdcCsarHelper) { + + List<NodeTemplate> nodes = new ArrayList<NodeTemplate>(); + nodes.addAll(nodeTemplates); + + for (NodeTemplate nodeTemplate : nodeTemplates) { + RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate); + List<RequirementAssignment> reqAs = requirement.getAll(); + for (RequirementAssignment ra : reqAs) { + String reqNode = ra.getNodeTemplateName(); + for (NodeTemplate rNode : resultList) { + if (rNode.getName().equals(reqNode)) { + if(!resultList.contains(nodeTemplate)) { + resultList.add(nodeTemplate); + } + if(nodes.contains(nodeTemplate)) { + nodes.remove(nodeTemplate); + } + break; + } + } + } + } + + if (!nodes.isEmpty()) { + getRequirementList(resultList, nodes, iSdcCsarHelper); + } + + return resultList; + } + + // This method retrieve resource sequence from csar file + void processResourceSequence(ToscaResourceStructure toscaResourceStructure, Service service) { + List<String> resouceSequence = new ArrayList<String>(); + List<NodeTemplate> resultList = new ArrayList<NodeTemplate>(); + + ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper(); + List<NodeTemplate> nodeTemplates = iSdcCsarHelper.getServiceNodeTemplates(); + List<NodeTemplate> nodes = new ArrayList<NodeTemplate>(); + nodes.addAll(nodeTemplates); + + for (NodeTemplate nodeTemplate : nodeTemplates) { + RequirementAssignments requirement = iSdcCsarHelper.getRequirementsOf(nodeTemplate); + + if (requirement == null || requirement.getAll() == null || requirement.getAll().isEmpty()) { + resultList.add(nodeTemplate); + nodes.remove(nodeTemplate); + } + } + + resultList = getRequirementList(resultList, nodes, iSdcCsarHelper); + + for (NodeTemplate node : resultList) { + String templateName = node.getMetaData().getValue("name"); + if (!resouceSequence.contains(templateName)) { + resouceSequence.add(templateName); + } + } + + String resourceSeqStr = resouceSequence.stream().collect(Collectors.joining(",")); + service.setResourceOrder(resourceSeqStr); + logger.debug(" resourceSeq for service uuid(" + service.getModelUUID() + ") : " + resourceSeqStr); + } + + private static String getValue(Object value, List<Input> servInputs) { + String output = null; + if(value instanceof Map) { + // currently this logic handles only one level of nesting. + return ((LinkedHashMap) value).values().toArray()[0].toString(); + } else if(value instanceof GetInput) { + String inputName = ((GetInput)value).getInputName(); + + for(Input input : servInputs) { + if(input.getName().equals(inputName)) { + // keep both input name and default value + // if service input does not supplies value the use default value + String defaultValue = input.getDefault() != null ? (String) input.getDefault().toString() : ""; + output = inputName + "|" + defaultValue;// return default value + } + } + + } else { + output = value != null ? value.toString() : ""; + } + return output; // return property value + } + + String getResourceInput(ToscaResourceStructure toscaResourceStructure, String resourceCustomizationUuid) throws ArtifactInstallerException { + Map<String, String> resouceRequest = new HashMap<>(); + ISdcCsarHelper iSdcCsarHelper = toscaResourceStructure.getSdcCsarHelper(); + + List<Input> serInput = iSdcCsarHelper.getServiceInputs(); + Optional<NodeTemplate> nodeTemplateOpt = iSdcCsarHelper.getServiceNodeTemplates().stream() + .filter(e -> e.getMetaData().getValue(CUSTOMIZATION_UUID).equals(resourceCustomizationUuid)).findFirst(); + if(nodeTemplateOpt.isPresent()) { + NodeTemplate nodeTemplate = nodeTemplateOpt.get(); + LinkedHashMap<String, Property> resourceProperties = nodeTemplate.getProperties(); + + for(String key : resourceProperties.keySet()) { + Property property = resourceProperties.get(key); + + String value = getValue(property.getValue(), serInput); + resouceRequest.put(key, value); + } + } + + try { + ObjectMapper objectMapper = new ObjectMapper(); + String jsonStr = objectMapper.writeValueAsString(resouceRequest); + + jsonStr = jsonStr.replace("\"", "\\\""); + logger.debug("resource request for resource customization id (" + resourceCustomizationUuid + ") : " + jsonStr); + return jsonStr; + } catch (JsonProcessingException e) { + logger.error("resource input could not be deserialized for resource customization id (" + + resourceCustomizationUuid + ")"); + throw new ArtifactInstallerException("resource input could not be parsed", e); + } + } + + protected void processNetworks (ToscaResourceStructure toscaResourceStruct, + Service service) throws ArtifactInstallerException { + List <NodeTemplate> nodeTemplatesVLList = toscaResourceStruct.getSdcCsarHelper ().getServiceVlList (); + + if (nodeTemplatesVLList != null) { + for (NodeTemplate vlNode : nodeTemplatesVLList) { + String networkResourceModelName = vlNode.getMetaData ().getValue (SdcPropertyNames.PROPERTY_NAME_NAME); + + TempNetworkHeatTemplateLookup tempNetworkLookUp = + tempNetworkLookupRepo.findFirstBynetworkResourceModelName (networkResourceModelName); + + if (tempNetworkLookUp != null) { + HeatTemplate heatTemplate = + heatRepo.findByArtifactUuid (tempNetworkLookUp.getHeatTemplateArtifactUuid ()); + if (heatTemplate != null) { + NetworkResourceCustomization networkCustomization = + createNetwork (vlNode, + toscaResourceStruct, + heatTemplate, + tempNetworkLookUp.getAicVersionMax (), + tempNetworkLookUp.getAicVersionMin (), + service); + service.getNetworkCustomizations ().add (networkCustomization); + } else { + throw new ArtifactInstallerException ("No HeatTemplate found for artifactUUID: " + + tempNetworkLookUp.getHeatTemplateArtifactUuid ()); + } + } else { + NetworkResourceCustomization networkCustomization = createNetwork (vlNode, + toscaResourceStruct, + null, + null, + null, + service); + service.getNetworkCustomizations().add (networkCustomization); + logger.debug ("No NetworkResourceName found in TempNetworkHeatTemplateLookup for " + + networkResourceModelName); + } + + } + } + } + + protected void processAllottedResources(ToscaResourceStructure toscaResourceStruct, Service service, + List<NodeTemplate> allottedResourceList) { + if (allottedResourceList != null) { + for (NodeTemplate allottedNode : allottedResourceList) { + service.getAllottedCustomizations() + .add(createAllottedResource(allottedNode, toscaResourceStruct, service)); + } + } + } + + + protected ConfigurationResource getConfigurationResource(NodeTemplate nodeTemplate) { + Metadata metadata = nodeTemplate.getMetaData(); + ConfigurationResource configResource = new ConfigurationResource(); + configResource.setModelName(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + configResource.setModelInvariantUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + configResource.setModelUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + configResource.setModelVersion(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + configResource.setDescription(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + configResource.setToscaNodeType(nodeTemplate.getType()); + return configResource; + } + + protected ConfigurationResourceCustomization getConfigurationResourceCustomization(NodeTemplate nodeTemplate, ToscaResourceStructure toscaResourceStructure, + ServiceProxyResourceCustomization spResourceCustomization ) { + Metadata metadata = nodeTemplate.getMetaData(); + + ConfigurationResource configResource = getConfigurationResource(nodeTemplate); + + ConfigurationResourceCustomization configCustomizationResource = new ConfigurationResourceCustomization(); + + Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>(); + + configCustomizationResource.setModelCustomizationUUID(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + configCustomizationResource.setModelInstanceName(nodeTemplate.getName()); + + configCustomizationResource.setNfFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION)); + configCustomizationResource.setNfRole(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE)); + configCustomizationResource.setNfType(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE)); + configCustomizationResource.setServiceProxyResourceCustomizationUUID(spResourceCustomization.getModelCustomizationUUID()); + + configCustomizationResource.setConfigurationResource(configResource); + configResourceCustomizationSet.add(configCustomizationResource); + + configResource.setConfigurationResourceCustomization(configResourceCustomizationSet); + return configCustomizationResource; + } + + + protected Optional<ConfigurationResourceCustomization> getVnrNodeTemplate(List<NodeTemplate> configurationNodeTemplatesList, + ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization) { + Optional<ConfigurationResourceCustomization> configurationResourceCust = Optional.empty(); + for (NodeTemplate nodeTemplate : configurationNodeTemplatesList) { + StatefulEntityType entityType = nodeTemplate.getTypeDefinition(); + String type = entityType.getType(); + + if(VLAN_NETWORK_RECEPTOR.equals(type)) { + configurationResourceCust= Optional.of(getConfigurationResourceCustomization(nodeTemplate, + toscaResourceStructure,spResourceCustomization)); + break; + } + } + + return configurationResourceCust; + } + + protected void processServiceProxyAndConfiguration(ToscaResourceStructure toscaResourceStruct, Service service) { + + List<NodeTemplate> serviceProxyResourceList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.SERVICE_PROXY); + + List<NodeTemplate> configurationNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CONFIGURATION); + + List<ServiceProxyResourceCustomization> serviceProxyList = new ArrayList<ServiceProxyResourceCustomization>(); + List<ConfigurationResourceCustomization> configurationResourceList = new ArrayList<ConfigurationResourceCustomization>(); + + ServiceProxyResourceCustomization serviceProxy = null; + + if (serviceProxyResourceList != null) { + for (NodeTemplate spNode : serviceProxyResourceList) { + serviceProxy = createServiceProxy(spNode, service, toscaResourceStruct); + serviceProxyList.add(serviceProxy); + Optional<ConfigurationResourceCustomization> vnrResourceCustomization = getVnrNodeTemplate(configurationNodeTemplatesList,toscaResourceStruct,serviceProxy); + + for (NodeTemplate configNode : configurationNodeTemplatesList) { + + List<RequirementAssignment> requirementsList = toscaResourceStruct.getSdcCsarHelper().getRequirementsOf(configNode).getAll(); + for (RequirementAssignment requirement : requirementsList) { + if (requirement.getNodeTemplateName().equals(spNode.getName())) { + ConfigurationResourceCustomization configurationResource = createConfiguration(configNode, toscaResourceStruct, serviceProxy, vnrResourceCustomization); + + Optional<ConfigurationResourceCustomization> matchingObject = configurationResourceList.stream() + .filter(configurationResourceCustomization -> configNode.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID).equals(configurationResource.getModelCustomizationUUID())) + .findFirst(); + if(!matchingObject.isPresent()){ + configurationResourceList.add(configurationResource); + } + + break; + } + } + } + + } + } + + service.setConfigurationCustomizations(configurationResourceList); + service.setServiceProxyCustomizations(serviceProxyList); + } + + protected void processNetworkCollections(ToscaResourceStructure toscaResourceStruct, Service service) { + + List<NodeTemplate> networkCollectionList = toscaResourceStruct.getSdcCsarHelper().getServiceNodeTemplateBySdcType(SdcTypes.CR); + + if (networkCollectionList != null) { + for (NodeTemplate crNode : networkCollectionList) { + + createNetworkCollection(crNode, toscaResourceStruct, service); + collectionRepo.saveAndFlush(toscaResourceStruct.getCatalogCollectionResource()); + + List<NetworkInstanceGroup> networkInstanceGroupList = toscaResourceStruct.getCatalogNetworkInstanceGroup(); + for(NetworkInstanceGroup networkInstanceGroup : networkInstanceGroupList){ + instanceGroupRepo.saveAndFlush(networkInstanceGroup); + } + + } + } + service.getCollectionResourceCustomizations().add(toscaResourceStruct.getCatalogCollectionResourceCustomization()); + } + + + protected void processVFResources (ToscaResourceStructure toscaResourceStruct, Service service, VfResourceStructure vfResourceStructure) + throws Exception{ + logger.debug("processVFResources"); + + List<NodeTemplate> vfNodeTemplatesList = toscaResourceStruct.getSdcCsarHelper().getServiceVfList(); +// String servicecategory = toscaResourceStruct.getCatalogService().getCategory(); +// String serviceType = toscaResourceStruct.getCatalogService().getServiceType(); + + for (NodeTemplate nodeTemplate : vfNodeTemplatesList) { + Metadata metadata = nodeTemplate.getMetaData(); + String vfCustomizationCategory = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY); + logger.debug("VF Category is : " + vfCustomizationCategory); + + // Do not treat Allotted Resources as VNF resources + if(ALLOTTED_RESOURCE.equalsIgnoreCase(vfCustomizationCategory)){ + continue; + } + + String vfCustomizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); + logger.debug("VFCustomizationUUID=" + vfCustomizationUUID); + + IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance(); + + // Make sure the VF ResourceCustomizationUUID from the notification and tosca + // customizations match before comparing their VF Modules UUID's + logger.debug("Checking if Notification VF ResourceCustomizationUUID: " + + vfNotificationResource.getResourceCustomizationUUID() + " matches Tosca VF Customization UUID: " + + vfCustomizationUUID); + + if (vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())) { + logger.debug("vfCustomizationUUID: " + vfCustomizationUUID + + " matches vfNotificationResource CustomizationUUID"); + + processVfModules(toscaResourceStruct, vfResourceStructure, service, nodeTemplate, metadata, + vfCustomizationCategory); + } else { + logger.debug("Notification VF ResourceCustomizationUUID: " + + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match " + + "Tosca VF Customization UUID: " + vfCustomizationUUID); + } + } + } + + /** + * This is used to process the PNF specific resource, including resource and resource_customization. {@link + * IEntityDetails} based API is used to retrieve information. Please check {@link ISdcCsarHelper} for details. + */ + protected void processPnfResources(ToscaResourceStructure toscaResourceStruct, Service service, + PnfResourceStructure resourceStructure) throws Exception { + logger.info("Processing PNF resource: {}", resourceStructure.getResourceInstance().getResourceUUID()); + + ISdcCsarHelper sdcCsarHelper = toscaResourceStruct.getSdcCsarHelper(); + EntityQuery entityQuery = EntityQuery.newBuilder(SdcTypes.PNF).build(); + TopologyTemplateQuery topologyTemplateQuery = TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build(); + + List<IEntityDetails> entityDetailsList = sdcCsarHelper.getEntity(entityQuery, topologyTemplateQuery, false); + for (IEntityDetails entityDetails : entityDetailsList) { + Metadata metadata = entityDetails.getMetadata(); + String customizationUUID = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); + String modelUuid = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID); + String notifCustomizationUUID = resourceStructure.getResourceInstance().getResourceCustomizationUUID(); + if (customizationUUID != null && customizationUUID.equals(notifCustomizationUUID)) { + logger.info("Resource customization UUID: {} is the same as notified resource customizationUUID: {}", + customizationUUID, notifCustomizationUUID); + + if (checkExistingPnfResourceCutomization(customizationUUID)) { + logger.info("Resource customization UUID: {} already deployed", customizationUUID); + } else { + PnfResource pnfResource = findExistingPnfResource(service, modelUuid); + if (pnfResource == null) { + pnfResource = createPnfResource(entityDetails); + } + PnfResourceCustomization pnfResourceCustomization = createPnfResourceCustomization(entityDetails, + pnfResource); + pnfResource.getPnfResourceCustomizations().add(pnfResourceCustomization); + toscaResourceStruct.setPnfResourceCustomization(pnfResourceCustomization); + service.getPnfCustomizations().add(pnfResourceCustomization); + } + } else { + logger + .warn("Resource customization UUID: {} is NOT the same as notified resource customizationUUID: {}", + customizationUUID, notifCustomizationUUID); + } + } + } + + private PnfResource findExistingPnfResource(Service service, String modelUuid) { + PnfResource pnfResource = null; + for (PnfResourceCustomization pnfResourceCustomization : service.getPnfCustomizations()) { + if (pnfResourceCustomization.getPnfResources() != null && pnfResourceCustomization.getPnfResources() + .getModelUUID().equals(modelUuid)) { + pnfResource = pnfResourceCustomization.getPnfResources(); + } + } + if (pnfResource == null) { + pnfResource = pnfResourceRepository.findById(modelUuid).orElse(pnfResource); + } + return pnfResource; + } + + private boolean checkExistingPnfResourceCutomization(String customizationUUID) { + return pnfCustomizationRepository.findById(customizationUUID).isPresent(); + } + + /** + * Construct the {@link PnfResource} from {@link IEntityDetails} object. + */ + private PnfResource createPnfResource(IEntityDetails entity) { + PnfResource pnfResource = new PnfResource(); + Metadata metadata = entity.getMetadata(); + pnfResource.setModelInvariantUUID( + testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + pnfResource.setModelName(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + pnfResource.setModelUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + pnfResource.setModelVersion( + testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + pnfResource.setDescription( + testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + pnfResource.setCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY))); + pnfResource.setSubCategory(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY))); + pnfResource.setToscaNodeType(entity.getToscaType()); + return pnfResource; + } + + /** + * Construct the {@link PnfResourceCustomization} from {@link IEntityDetails} object. + */ + private PnfResourceCustomization createPnfResourceCustomization(IEntityDetails entityDetails, + PnfResource pnfResource) { + + PnfResourceCustomization pnfResourceCustomization = new PnfResourceCustomization(); + Metadata metadata = entityDetails.getMetadata(); + Map<String, Property> properties = entityDetails.getProperties(); + pnfResourceCustomization + .setModelCustomizationUUID(testNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + pnfResourceCustomization.setModelInstanceName(entityDetails.getName()); + pnfResourceCustomization + .setNfFunction(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); + pnfResourceCustomization.setNfNamingCode(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFCODE))); + pnfResourceCustomization.setNfRole(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFROLE))); + pnfResourceCustomization.setNfType(getStringValue(properties.get(SdcPropertyNames.PROPERTY_NAME_NFTYPE))); + pnfResourceCustomization.setMultiStageDesign(getStringValue(properties.get(MULTI_STAGE_DESIGN))); + pnfResourceCustomization.setBlueprintName(getStringValue(properties.get(SDNC_MODEL_NAME))); + pnfResourceCustomization.setBlueprintVersion(getStringValue(properties.get(SDNC_MODEL_VERSION))); + + pnfResourceCustomization.setPnfResources(pnfResource); + + return pnfResourceCustomization; + } + + /** + * Get value from {@link Property} and cast to String value. Return empty String if property is null value. + */ + private String getStringValue(Property property) { + if (null == property) { + return ""; + } + Object value = property.getValue(); + return String.valueOf(value); + } + + protected void processVfModules(ToscaResourceStructure toscaResourceStruct, VfResourceStructure vfResourceStructure, + Service service, NodeTemplate nodeTemplate, Metadata metadata, String vfCustomizationCategory) throws Exception { + + logger.debug("VF Category is : " + vfCustomizationCategory); + + if(vfResourceStructure.getVfModuleStructure() != null && !vfResourceStructure.getVfModuleStructure().isEmpty()) + { + + String vfCustomizationUUID = toscaResourceStruct.getSdcCsarHelper() + .getMetadataPropertyValue(metadata, SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); + logger.debug("VFCustomizationUUID=" + vfCustomizationUUID); + + IResourceInstance vfNotificationResource = vfResourceStructure.getResourceInstance(); + + // Make sure the VF ResourceCustomizationUUID from the notification and tosca customizations match before comparing their VF Modules UUID's + logger.debug("Checking if Notification VF ResourceCustomizationUUID: " + vfNotificationResource.getResourceCustomizationUUID() + + " matches Tosca VF Customization UUID: " + vfCustomizationUUID); + + if(vfCustomizationUUID.equals(vfNotificationResource.getResourceCustomizationUUID())){ + + logger.debug("vfCustomizationUUID: " + vfCustomizationUUID + " matches vfNotificationResource CustomizationUUID"); + + VnfResourceCustomization vnfResource = createVnfResource(nodeTemplate, toscaResourceStruct, service); + + Set<CvnfcCustomization> existingCvnfcSet = new HashSet<CvnfcCustomization>(); + Set<VnfcCustomization> existingVnfcSet = new HashSet<VnfcCustomization>(); + + for (VfModuleStructure vfModuleStructure : vfResourceStructure.getVfModuleStructure()) { + + logger.debug("vfModuleStructure:" + vfModuleStructure.toString()); + List<org.onap.sdc.toscaparser.api.Group> vfGroups = toscaResourceStruct + .getSdcCsarHelper().getVfModulesByVf(vfCustomizationUUID); + IVfModuleData vfMetadata = vfModuleStructure.getVfModuleMetadata(); + + logger.debug("Comparing Vf_Modules_Metadata CustomizationUUID : " + vfMetadata.getVfModuleModelCustomizationUUID()); + + Optional<org.onap.sdc.toscaparser.api.Group> matchingObject = vfGroups.stream() + .peek(group -> logger.debug("To Csar Group VFModuleModelCustomizationUUID " + group.getMetadata().getValue("vfModuleModelCustomizationUUID"))) + .filter(group -> group.getMetadata().getValue("vfModuleModelCustomizationUUID").equals(vfMetadata.getVfModuleModelCustomizationUUID())) + .findFirst(); + if(matchingObject.isPresent()){ + VfModuleCustomization vfModuleCustomization = createVFModuleResource(matchingObject.get(), nodeTemplate, toscaResourceStruct, + vfResourceStructure,vfMetadata, vnfResource, service, existingCvnfcSet, existingVnfcSet); + vfModuleCustomization.getVfModule().setVnfResources(vnfResource.getVnfResources()); + }else + throw new Exception("Cannot find matching VFModule Customization in Csar for Vf_Modules_Metadata: " + vfMetadata.getVfModuleModelCustomizationUUID()); + + } + service.getVnfCustomizations().add(vnfResource); + } else{ + logger.debug("Notification VF ResourceCustomizationUUID: " + vfNotificationResource.getResourceCustomizationUUID() + " doesn't match " + + "Tosca VF Customization UUID: " + vfCustomizationUUID); + } + } + } + + public void processWatchdog(String distributionId, String servideUUID, Optional<String> distributionNotification, + String consumerId) { + WatchdogServiceModVerIdLookup modVerIdLookup = new WatchdogServiceModVerIdLookup(distributionId, servideUUID, + distributionNotification, consumerId); + watchdogModVerIdLookupRepository.saveAndFlush(modVerIdLookup); + + try{ + + WatchdogDistributionStatus distributionStatus = new WatchdogDistributionStatus(distributionId); + watchdogDistributionStatusRepository.saveAndFlush(distributionStatus); + + } catch(ObjectOptimisticLockingFailureException e){ + logger.debug("ObjectOptimisticLockingFailureException in processWatchdog : " + e.toString()); + throw e; + } + } + + protected void extractHeatInformation(ToscaResourceStructure toscaResourceStruct, + VfResourceStructure vfResourceStructure) { + for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { + + switch (vfModuleArtifact.getArtifactInfo().getArtifactType()) { + case ASDCConfiguration.HEAT: + case ASDCConfiguration.HEAT_NESTED: + createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, + vfModuleArtifact); + break; + case ASDCConfiguration.HEAT_VOL: + createHeatTemplateFromArtifact(vfResourceStructure, toscaResourceStruct, + vfModuleArtifact); + VfModuleArtifact envModuleArtifact = getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact); + createHeatEnvFromArtifact(vfResourceStructure, envModuleArtifact); + break; + case ASDCConfiguration.HEAT_ENV: + createHeatEnvFromArtifact(vfResourceStructure, vfModuleArtifact); + break; + case ASDCConfiguration.HEAT_ARTIFACT: + createHeatFileFromArtifact(vfResourceStructure, vfModuleArtifact, + toscaResourceStruct); + break; + case ASDCConfiguration.HEAT_NET: + case ASDCConfiguration.OTHER: + logger.warn("{} {} {} {}", MessageEnum.ASDC_ARTIFACT_TYPE_NOT_SUPPORT.toString(), + vfModuleArtifact.getArtifactInfo().getArtifactType() + "(Artifact Name:" + vfModuleArtifact.getArtifactInfo() + .getArtifactName() + ")", ErrorCode.DataError.getValue(), "Artifact type not supported"); + break; + default: + break; + + } + } + } + + protected VfModuleArtifact getHeatEnvArtifactFromGeneratedArtifact(VfResourceStructure vfResourceStructure, + VfModuleArtifact vfModuleArtifact) { + String artifactName = vfModuleArtifact.getArtifactInfo().getArtifactName(); + artifactName = artifactName.substring(0, artifactName.indexOf('.')); + for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { + if (moduleArtifact.getArtifactInfo().getArtifactName().contains(artifactName) + && moduleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) { + return moduleArtifact; + } + } + return null; + } + + public String verifyTheFilePrefixInArtifacts(String filebody, VfResourceStructure vfResourceStructure, + List<String> listTypes) { + String newFileBody = filebody; + for (VfModuleArtifact moduleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { + + if (listTypes.contains(moduleArtifact.getArtifactInfo().getArtifactType())) { + + newFileBody = verifyTheFilePrefixInString(newFileBody, + moduleArtifact.getArtifactInfo().getArtifactName()); + } + } + return newFileBody; + } + + public String verifyTheFilePrefixInString(final String body, final String filenameToVerify) { + + String needlePrefix = "file:///"; + String prefixedFilenameToVerify = needlePrefix + filenameToVerify; + + if ((body == null) || (body.length() == 0) || (filenameToVerify == null) || (filenameToVerify.length() == 0)) { + return body; + } + + StringBuilder sb = new StringBuilder(body.length()); + + int currentIndex = 0; + int startIndex = 0; + + while (currentIndex != -1) { + startIndex = currentIndex; + currentIndex = body.indexOf(prefixedFilenameToVerify, startIndex); + + if (currentIndex == -1) { + break; + } + // We append from the startIndex up to currentIndex (start of File + // Name) + sb.append(body.substring(startIndex, currentIndex)); + sb.append(filenameToVerify); + + currentIndex += prefixedFilenameToVerify.length(); + } + + sb.append(body.substring(startIndex)); + + return sb.toString(); + } + + protected void createHeatTemplateFromArtifact(VfResourceStructure vfResourceStructure, + ToscaResourceStructure toscaResourceStruct, VfModuleArtifact vfModuleArtifact) { + HeatTemplate heatTemplate = new HeatTemplate(); + List<String> typeList = new ArrayList<>(); + typeList.add(ASDCConfiguration.HEAT_NESTED); + typeList.add(ASDCConfiguration.HEAT_ARTIFACT); + + heatTemplate.setTemplateBody( + verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); + heatTemplate.setTemplateName(vfModuleArtifact.getArtifactInfo().getArtifactName()); + + if (vfModuleArtifact.getArtifactInfo().getArtifactTimeout() != null) { + heatTemplate.setTimeoutMinutes(vfModuleArtifact.getArtifactInfo().getArtifactTimeout()); + } else { + heatTemplate.setTimeoutMinutes(240); + } + + heatTemplate.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); + heatTemplate.setVersion(BigDecimalVersion + .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); + heatTemplate.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + + if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { + heatTemplate.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); + } else { + heatTemplate.setArtifactChecksum(MANUAL_RECORD); + } + + Set<HeatTemplateParam> heatParam = extractHeatTemplateParameters( + vfModuleArtifact.getResult(), vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + heatTemplate.setParameters(heatParam); + vfModuleArtifact.setHeatTemplate(heatTemplate); + } + + protected void createHeatEnvFromArtifact(VfResourceStructure vfResourceStructure, + VfModuleArtifact vfModuleArtifact) { + HeatEnvironment heatEnvironment = new HeatEnvironment(); + heatEnvironment.setName(vfModuleArtifact.getArtifactInfo().getArtifactName()); + List<String> typeList = new ArrayList<>(); + typeList.add(ASDCConfiguration.HEAT); + typeList.add(ASDCConfiguration.HEAT_VOL); + heatEnvironment.setEnvironment( + verifyTheFilePrefixInArtifacts(vfModuleArtifact.getResult(), vfResourceStructure, typeList)); + heatEnvironment.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); + heatEnvironment.setVersion(BigDecimalVersion + .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); + heatEnvironment.setArtifactUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + + if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { + heatEnvironment.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); + } else { + heatEnvironment.setArtifactChecksum(MANUAL_RECORD); + } + vfModuleArtifact.setHeatEnvironment(heatEnvironment); + } + + protected void createHeatFileFromArtifact(VfResourceStructure vfResourceStructure, + VfModuleArtifact vfModuleArtifact, ToscaResourceStructure toscaResourceStruct) { + + HeatFiles heatFile = new HeatFiles(); + heatFile.setAsdcUuid(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + heatFile.setDescription(vfModuleArtifact.getArtifactInfo().getArtifactDescription()); + heatFile.setFileBody(vfModuleArtifact.getResult()); + heatFile.setFileName(vfModuleArtifact.getArtifactInfo().getArtifactName()); + heatFile.setVersion(BigDecimalVersion + .castAndCheckNotificationVersionToString(vfModuleArtifact.getArtifactInfo().getArtifactVersion())); + toscaResourceStruct.setHeatFilesUUID(vfModuleArtifact.getArtifactInfo().getArtifactUUID()); + if (vfModuleArtifact.getArtifactInfo().getArtifactChecksum() != null) { + heatFile.setArtifactChecksum(vfModuleArtifact.getArtifactInfo().getArtifactChecksum()); + } else { + heatFile.setArtifactChecksum(MANUAL_RECORD); + } + vfModuleArtifact.setHeatFiles(heatFile); + } + + protected Service createService(ToscaResourceStructure toscaResourceStructure, + ResourceStructure resourceStructure) { + + Metadata serviceMetadata = toscaResourceStructure.getServiceMetadata(); + + Service service = new Service(); + + if (serviceMetadata != null) { + + if (toscaResourceStructure.getServiceVersion() != null) { + service.setModelVersion(toscaResourceStructure.getServiceVersion()); + } + + service.setServiceType(serviceMetadata.getValue("serviceType")); + service.setServiceRole(serviceMetadata.getValue("serviceRole")); + service.setCategory(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)); + + service.setDescription(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + service.setModelName(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + service.setModelUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + service.setEnvironmentContext(serviceMetadata.getValue("environmentContext")); + + if (resourceStructure != null) + service.setWorkloadContext(resourceStructure.getNotification().getWorkloadContext()); + + service.setModelInvariantUUID(serviceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + service.setCsar(toscaResourceStructure.getCatalogToscaCsar()); + } + + + toscaResourceStructure.setCatalogService(service); + return service; + } + + protected ServiceProxyResourceCustomization createServiceProxy(NodeTemplate nodeTemplate, Service service, ToscaResourceStructure toscaResourceStructure) { + + Metadata spMetadata = nodeTemplate.getMetaData(); + + ServiceProxyResourceCustomization spCustomizationResource = new ServiceProxyResourceCustomization(); + + Set<ServiceProxyResourceCustomization> serviceProxyCustomizationSet = new HashSet<>(); + + spCustomizationResource.setModelName(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + spCustomizationResource.setModelInvariantUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + spCustomizationResource.setModelUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + spCustomizationResource.setModelVersion(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + spCustomizationResource.setDescription(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + + spCustomizationResource.setModelCustomizationUUID(spMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + spCustomizationResource.setModelInstanceName(nodeTemplate.getName()); + spCustomizationResource.setToscaNodeType(nodeTemplate.getType()); + + String sourceServiceUUID = spMetadata.getValue("sourceModelUuid"); + + Service sourceService = serviceRepo.findOneByModelUUID(sourceServiceUUID); + + spCustomizationResource.setSourceService(sourceService); + spCustomizationResource.setToscaNodeType(nodeTemplate.getType()); + serviceProxyCustomizationSet.add(spCustomizationResource); + + + toscaResourceStructure.setCatalogServiceProxyResourceCustomization(spCustomizationResource); + + return spCustomizationResource; + } + + protected ConfigurationResourceCustomization createConfiguration(NodeTemplate nodeTemplate, + ToscaResourceStructure toscaResourceStructure, ServiceProxyResourceCustomization spResourceCustomization, + Optional<ConfigurationResourceCustomization> vnrResourceCustomization) { + + ConfigurationResourceCustomization configCustomizationResource = getConfigurationResourceCustomization(nodeTemplate, + toscaResourceStructure,spResourceCustomization); + + ConfigurationResource configResource = getConfigurationResource(nodeTemplate); + + Set<ConfigurationResourceCustomization> configResourceCustomizationSet = new HashSet<>(); + + StatefulEntityType entityType = nodeTemplate.getTypeDefinition(); + String type = entityType.getType(); + + if(NODES_VRF_ENTRY.equals(type)) { + configCustomizationResource.setConfigResourceCustomization(vnrResourceCustomization.orElse(null)); + } + + configCustomizationResource.setConfigurationResource(configResource); + + configResourceCustomizationSet.add(configCustomizationResource); + + configResource.setConfigurationResourceCustomization(configResourceCustomizationSet); + + toscaResourceStructure.setCatalogConfigurationResource(configResource); + + toscaResourceStructure.setCatalogConfigurationResourceCustomization(configCustomizationResource); + + return configCustomizationResource; + } + + protected ConfigurationResource createFabricConfiguration(NodeTemplate nodeTemplate, ToscaResourceStructure toscaResourceStructure) { + + Metadata fabricMetadata = nodeTemplate.getMetaData(); + + ConfigurationResource configResource = new ConfigurationResource(); + + configResource.setModelName(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + configResource.setModelInvariantUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + configResource.setModelUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + configResource.setModelVersion(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + configResource.setDescription(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + configResource.setToscaNodeType(nodeTemplate.getType()); + + return configResource; + } + + protected void createToscaCsar(ToscaResourceStructure toscaResourceStructure) { + ToscaCsar toscaCsar = new ToscaCsar(); + if (toscaResourceStructure.getToscaArtifact().getArtifactChecksum() != null) { + toscaCsar.setArtifactChecksum(toscaResourceStructure.getToscaArtifact().getArtifactChecksum()); + } else { + toscaCsar.setArtifactChecksum(MANUAL_RECORD); + } + toscaCsar.setArtifactUUID(toscaResourceStructure.getToscaArtifact().getArtifactUUID()); + toscaCsar.setName(toscaResourceStructure.getToscaArtifact().getArtifactName()); + toscaCsar.setVersion(toscaResourceStructure.getToscaArtifact().getArtifactVersion()); + toscaCsar.setDescription(toscaResourceStructure.getToscaArtifact().getArtifactDescription()); + toscaCsar.setUrl(toscaResourceStructure.getToscaArtifact().getArtifactURL()); + + toscaResourceStructure.setCatalogToscaCsar(toscaCsar); + } + + protected VnfcCustomization findExistingVfc(Set<VnfcCustomization> vnfcCustomizations, String customizationUUID) { + VnfcCustomization vnfcCustomization = null; + for(VnfcCustomization vnfcCustom : vnfcCustomizations){ + if (vnfcCustom != null && vnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) { + vnfcCustomization = vnfcCustom; + } + } + + if(vnfcCustomization==null) + vnfcCustomization = vnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID); + + return vnfcCustomization; + } + + protected CvnfcCustomization findExistingCvfc(Set<CvnfcCustomization> cvnfcCustomizations, String customizationUUID) { + CvnfcCustomization cvnfcCustomization = null; + for(CvnfcCustomization cvnfcCustom : cvnfcCustomizations){ + if (cvnfcCustom != null && cvnfcCustom.getModelCustomizationUUID().equals(customizationUUID)) { + cvnfcCustomization = cvnfcCustom; + } + } + + if(cvnfcCustomization==null) + cvnfcCustomization = cvnfcCustomizationRepo.findOneByModelCustomizationUUID(customizationUUID); + + return cvnfcCustomization; + } + + protected NetworkResourceCustomization createNetwork(NodeTemplate networkNodeTemplate, + ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin,Service service) { + + NetworkResourceCustomization networkResourceCustomization=networkCustomizationRepo.findOneByModelCustomizationUUID(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + boolean networkUUIDsMatch = true; + // Check to make sure the NetworkResourceUUID on the Customization record matches the NetworkResourceUUID from the distribution. + // If not we'll update the Customization record with latest from the distribution + if(networkResourceCustomization != null){ + String existingNetworkModelUUID = networkResourceCustomization.getNetworkResource().getModelUUID(); + String latestNetworkModelUUID = networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID); + + if(!existingNetworkModelUUID.equals(latestNetworkModelUUID)){ + networkUUIDsMatch = false; + } + + } + + if (networkResourceCustomization!=null && !networkUUIDsMatch){ + + NetworkResource networkResource = createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate, + aicMax, aicMin); + + networkResourceCustomization.setNetworkResource(networkResource); + + networkCustomizationRepo.saveAndFlush(networkResourceCustomization); + + } + else if(networkResourceCustomization==null){ + networkResourceCustomization = createNetworkResourceCustomization(networkNodeTemplate, + toscaResourceStructure); + + NetworkResource networkResource = findExistingNetworkResource(service, + networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + if(networkResource == null) + networkResource = createNetworkResource(networkNodeTemplate, toscaResourceStructure, heatTemplate, + aicMax, aicMin); + + networkResource.addNetworkResourceCustomization(networkResourceCustomization); + networkResourceCustomization.setNetworkResource(networkResource); + } + + return networkResourceCustomization; + } + + protected NetworkResource findExistingNetworkResource(Service service, String modelUUID) { + NetworkResource networkResource = null; + for(NetworkResourceCustomization networkCustom : service.getNetworkCustomizations()){ + if (networkCustom.getNetworkResource() != null + && networkCustom.getNetworkResource().getModelUUID().equals(modelUUID)) { + networkResource = networkCustom.getNetworkResource(); + } + } + if(networkResource==null) + networkResource = networkRepo.findResourceByModelUUID(modelUUID); + + return networkResource; + } + + protected NetworkResourceCustomization createNetworkResourceCustomization(NodeTemplate networkNodeTemplate, + ToscaResourceStructure toscaResourceStructure) { + NetworkResourceCustomization networkResourceCustomization = new NetworkResourceCustomization(); + networkResourceCustomization.setModelInstanceName( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + networkResourceCustomization.setModelCustomizationUUID( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + + networkResourceCustomization.setNetworkTechnology( + testNull(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY))); + networkResourceCustomization.setNetworkType(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE))); + networkResourceCustomization.setNetworkRole(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE))); + networkResourceCustomization.setNetworkScope(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE))); + return networkResourceCustomization; + } + + protected NetworkResource createNetworkResource(NodeTemplate networkNodeTemplate, + ToscaResourceStructure toscaResourceStructure, HeatTemplate heatTemplate, String aicMax, String aicMin) { + NetworkResource networkResource = new NetworkResource(); + String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue( + networkNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK); + + if ("true".equalsIgnoreCase(providerNetwork)) { + networkResource.setNeutronNetworkType(PROVIDER); + } else { + networkResource.setNeutronNetworkType(BASIC); + } + + networkResource.setModelName( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + + networkResource.setModelInvariantUUID( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + networkResource.setModelUUID( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + networkResource.setModelVersion( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + + networkResource.setAicVersionMax(aicMax); + networkResource.setAicVersionMin(aicMin); + networkResource.setToscaNodeType(networkNodeTemplate.getType()); + networkResource.setDescription( + testNull(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + networkResource.setOrchestrationMode(HEAT); + networkResource.setHeatTemplate(heatTemplate); + return networkResource; + } + + protected CollectionNetworkResourceCustomization createNetworkCollection(NodeTemplate networkNodeTemplate, + ToscaResourceStructure toscaResourceStructure, Service service) { + + CollectionNetworkResourceCustomization collectionNetworkResourceCustomization = new CollectionNetworkResourceCustomization(); + + // **** Build Object to populate Collection_Resource table + CollectionResource collectionResource = new CollectionResource(); + + collectionResource + .setModelName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + collectionResource.setModelInvariantUUID( + networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + collectionResource + .setModelUUID(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + collectionResource + .setModelVersion(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + collectionResource + .setDescription(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + collectionResource.setToscaNodeType(networkNodeTemplate.getType()); + + toscaResourceStructure.setCatalogCollectionResource(collectionResource); + + // **** Build object to populate Collection_Resource_Customization table + NetworkCollectionResourceCustomization ncfc = new NetworkCollectionResourceCustomization(); + + ncfc.setFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + "cr_function")); + ncfc.setRole(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + "cr_role")); + ncfc.setType(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + "cr_type")); + + ncfc.setModelInstanceName(networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + ncfc.setModelCustomizationUUID( + networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + Set<CollectionNetworkResourceCustomization> networkResourceCustomizationSet = new HashSet<>(); + networkResourceCustomizationSet.add(collectionNetworkResourceCustomization); + + ncfc.setNetworkResourceCustomization(networkResourceCustomizationSet); + + ncfc.setCollectionResource(collectionResource); + toscaResourceStructure.setCatalogCollectionResourceCustomization(ncfc); + + //*** Build object to populate the Instance_Group table + List<Group> groupList = toscaResourceStructure.getSdcCsarHelper() + .getGroupsOfOriginOfNodeTemplateByToscaGroupType(networkNodeTemplate, + "org.openecomp.groups.NetworkCollection"); + + List<NetworkInstanceGroup> networkInstanceGroupList = new ArrayList<>(); + + List<CollectionResourceInstanceGroupCustomization> collectionResourceInstanceGroupCustomizationList = new ArrayList<CollectionResourceInstanceGroupCustomization>(); + + for (Group group : groupList) { + + NetworkInstanceGroup networkInstanceGroup = new NetworkInstanceGroup(); + Metadata instanceMetadata = group.getMetadata(); + networkInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + networkInstanceGroup + .setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + networkInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + networkInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + networkInstanceGroup.setToscaNodeType(group.getType()); + networkInstanceGroup.setRole(SubType.SUB_INTERFACE.toString()); // Set + // Role + networkInstanceGroup.setType(InstanceGroupType.L3_NETWORK); // Set + // type + networkInstanceGroup.setCollectionResource(collectionResource); + + // ****Build object to populate + // Collection_Resource_Instance_Group_Customization table + CollectionResourceInstanceGroupCustomization crInstanceGroupCustomization = new CollectionResourceInstanceGroupCustomization(); + crInstanceGroupCustomization.setInstanceGroup(networkInstanceGroup); + crInstanceGroupCustomization.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + crInstanceGroupCustomization.setModelCustomizationUUID( + networkNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + // Loop through the template policy to find the subinterface_network_quantity property name. Then extract the value for it. + List<Policy> policyList = toscaResourceStructure.getSdcCsarHelper().getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(networkNodeTemplate, "org.openecomp.policies.scaling.Fixed"); + + if(policyList != null){ + for(Policy policy : policyList){ + for(String policyNetworkCollection : policy.getTargets()){ + + if(policyNetworkCollection.equalsIgnoreCase(group.getName())){ + + Map<String, Object> propMap = policy.getPolicyProperties(); + + if(propMap.get("quantity") != null){ + + String quantity = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, getPropertyInput(propMap.get("quantity").toString())); + + if(quantity != null){ + crInstanceGroupCustomization.setSubInterfaceNetworkQuantity(Integer.parseInt(quantity)); + } + + } + + } + } + } + } + + crInstanceGroupCustomization.setDescription( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME) + + "_network_collection_description")); + crInstanceGroupCustomization.setFunction( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(networkNodeTemplate, + instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME) + + "_network_collection_function")); + crInstanceGroupCustomization.setCollectionResourceCust(ncfc); + collectionResourceInstanceGroupCustomizationList.add(crInstanceGroupCustomization); + + networkInstanceGroup + .setCollectionInstanceGroupCustomizations(collectionResourceInstanceGroupCustomizationList); + + networkInstanceGroupList.add(networkInstanceGroup); + + + toscaResourceStructure.setCatalogNetworkInstanceGroup(networkInstanceGroupList); + + List<NodeTemplate> vlNodeList = toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplateBySdcType(networkNodeTemplate, SdcTypes.VL); + + List<CollectionNetworkResourceCustomization> collectionNetworkResourceCustomizationList = new ArrayList<>(); + + //*****Build object to populate the NetworkResource table + NetworkResource networkResource = new NetworkResource(); + + for(NodeTemplate vlNodeTemplate : vlNodeList){ + + String providerNetwork = toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue( + vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK); + + if ("true".equalsIgnoreCase(providerNetwork)) { + networkResource.setNeutronNetworkType(PROVIDER); + } else { + networkResource.setNeutronNetworkType(BASIC); + } + + networkResource.setModelName(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + + networkResource.setModelInvariantUUID( + vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + networkResource.setModelUUID(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + networkResource + .setModelVersion(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + + networkResource.setAicVersionMax( + vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES)); + + TempNetworkHeatTemplateLookup tempNetworkLookUp = tempNetworkLookupRepo.findFirstBynetworkResourceModelName( + vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + + if (tempNetworkLookUp != null ) { + + HeatTemplate heatTemplate = heatRepo + .findByArtifactUuid(tempNetworkLookUp.getHeatTemplateArtifactUuid()); + networkResource.setHeatTemplate(heatTemplate); + + networkResource.setAicVersionMin(tempNetworkLookUp.getAicVersionMin()); + + } + + networkResource.setToscaNodeType(vlNodeTemplate.getType()); + networkResource + .setDescription(vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + networkResource.setOrchestrationMode(HEAT); + + // Build object to populate the + // Collection_Network_Resource_Customization table + for (NodeTemplate memberNode : group.getMemberNodes()) { + collectionNetworkResourceCustomization.setModelInstanceName(memberNode.getName()); + } + + collectionNetworkResourceCustomization.setModelCustomizationUUID( + vlNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + collectionNetworkResourceCustomization.setNetworkTechnology( + toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vlNodeTemplate, + SdcPropertyNames.PROPERTY_NAME_NETWORKTECHNOLOGY)); + collectionNetworkResourceCustomization.setNetworkType(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKTYPE)); + collectionNetworkResourceCustomization.setNetworkRole(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKROLE)); + collectionNetworkResourceCustomization.setNetworkScope(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vlNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NETWORKSCOPE)); + collectionNetworkResourceCustomization.setInstanceGroup(networkInstanceGroup); + collectionNetworkResourceCustomization.setNetworkResource(networkResource); + collectionNetworkResourceCustomization.setNetworkResourceCustomization(ncfc); + + collectionNetworkResourceCustomizationList.add(collectionNetworkResourceCustomization); + } + + } + + return collectionNetworkResourceCustomization; + } + + protected VnfcInstanceGroupCustomization createVNFCInstanceGroup(NodeTemplate vnfcNodeTemplate, Group group, + VnfResourceCustomization vnfResourceCustomization, ToscaResourceStructure toscaResourceStructure) { + + Metadata instanceMetadata = group.getMetadata(); + // Populate InstanceGroup + VFCInstanceGroup vfcInstanceGroup = new VFCInstanceGroup(); + + vfcInstanceGroup.setModelName(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + vfcInstanceGroup.setModelInvariantUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + vfcInstanceGroup.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + vfcInstanceGroup.setModelVersion(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VERSION)); + vfcInstanceGroup.setToscaNodeType(group.getType()); + vfcInstanceGroup.setRole("SUB-INTERFACE"); // Set Role + vfcInstanceGroup.setType(InstanceGroupType.VNFC); // Set type + + //Populate VNFCInstanceGroupCustomization + VnfcInstanceGroupCustomization vfcInstanceGroupCustom = new VnfcInstanceGroupCustomization(); + + vfcInstanceGroupCustom.setModelCustomizationUUID(vnfResourceCustomization.getModelCustomizationUUID()); + vfcInstanceGroupCustom.setModelUUID(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + vfcInstanceGroupCustom.setDescription(instanceMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + + String getInputName = null; + String groupProperty = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, "vfc_instance_group_function"); + if (groupProperty != null) { + int getInputIndex = groupProperty.indexOf("{get_input="); + if (getInputIndex > -1) { + getInputName = groupProperty.substring(getInputIndex+11, groupProperty.length()-1); + } + } + vfcInstanceGroupCustom.setFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vnfcNodeTemplate, getInputName)); + + vfcInstanceGroupCustom.setInstanceGroup(vfcInstanceGroup); + vfcInstanceGroupCustom.setVnfResourceCust(vnfResourceCustomization); + + return vfcInstanceGroupCustom; + + } + + protected VfModuleCustomization createVFModuleResource(Group group, NodeTemplate vfTemplate, + ToscaResourceStructure toscaResourceStructure, VfResourceStructure vfResourceStructure, + IVfModuleData vfModuleData, VnfResourceCustomization vnfResource, Service service, Set<CvnfcCustomization> existingCvnfcSet, Set<VnfcCustomization> existingVnfcSet) { + + VfModuleCustomization vfModuleCustomization = findExistingVfModuleCustomization(vnfResource, + vfModuleData.getVfModuleModelCustomizationUUID()); + if(vfModuleCustomization == null){ + VfModule vfModule = findExistingVfModule(vnfResource, + vfTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); + Metadata vfMetadata = group.getMetadata(); + if(vfModule==null) + vfModule=createVfModule(group, toscaResourceStructure, vfModuleData, vfMetadata); + + vfModuleCustomization = createVfModuleCustomization(group, toscaResourceStructure, vfModule, vfModuleData); + setHeatInformationForVfModule(toscaResourceStructure, vfResourceStructure, vfModule, vfModuleCustomization, + vfMetadata); + vfModuleCustomization.setVfModule(vfModule); + vfModule.getVfModuleCustomization().add(vfModuleCustomization); + vnfResource.getVfModuleCustomizations().add(vfModuleCustomization); + } else { + vfResourceStructure.setAlreadyDeployed(true); + } + + //****************************************************************************************************************** + //* Extract VFC's and CVFC's then add them to VFModule + //****************************************************************************************************************** + + Set<VnfVfmoduleCvnfcConfigurationCustomization> vnfVfmoduleCvnfcConfigurationCustomizations = new HashSet<VnfVfmoduleCvnfcConfigurationCustomization>(); + Set<CvnfcCustomization> cvnfcCustomizations = new HashSet<CvnfcCustomization>(); + Set<VnfcCustomization> vnfcCustomizations = new HashSet<VnfcCustomization>(); + + // Only set the CVNFC if this vfModule group is a member of it. + List<NodeTemplate> groupMembers = toscaResourceStructure.getSdcCsarHelper().getMembersOfVfModule(vfTemplate, group); + String vfModuleMemberName = null; + + // Extract CVFC lists + List<NodeTemplate> cvfcList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfTemplate, SdcTypes.CVFC); + + for(NodeTemplate cvfcTemplate : cvfcList) { + + boolean cvnfcVfModuleNameMatch = false; + + for(NodeTemplate node : groupMembers){ + vfModuleMemberName = node.getName(); + + if(vfModuleMemberName.equalsIgnoreCase(cvfcTemplate.getName())){ + cvnfcVfModuleNameMatch = true; + break; + } + } + + if(vfModuleMemberName != null && cvnfcVfModuleNameMatch){ + + //Extract associated VFC - Should always be just one + List<NodeTemplate> vfcList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(cvfcTemplate, SdcTypes.VFC); + + for(NodeTemplate vfcTemplate : vfcList) { + + VnfcCustomization vnfcCustomization = new VnfcCustomization(); + VnfcCustomization existingVnfcCustomization = null; + + existingVnfcCustomization = findExistingVfc(existingVnfcSet, vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + if(existingVnfcCustomization == null){ + vnfcCustomization = new VnfcCustomization(); + } else { + vnfcCustomization = existingVnfcCustomization; + } + + // Only Add Abstract VNFC's to our DB, ignore all others + if(existingVnfcCustomization == null && vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY).equalsIgnoreCase("Abstract")){ + vnfcCustomization.setModelCustomizationUUID(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + vnfcCustomization.setModelInstanceName(vfcTemplate.getName()); + vnfcCustomization.setModelInvariantUUID(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + vnfcCustomization.setModelName(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + vnfcCustomization.setModelUUID(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + + vnfcCustomization.setModelVersion( + testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + vnfcCustomization.setDescription( + testNull(vfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + vnfcCustomization.setToscaNodeType(testNull(vfcTemplate.getType())); + + vnfcCustomizations.add(vnfcCustomization); + existingVnfcSet.add(vnfcCustomization); + } + + // This check is needed incase the VFC subcategory is something other than Abstract. In that case we want to skip adding that record to our DB. + if(vnfcCustomization.getModelCustomizationUUID() != null){ + + CvnfcCustomization cvnfcCustomization = new CvnfcCustomization(); + + cvnfcCustomization = new CvnfcCustomization(); + cvnfcCustomization.setModelCustomizationUUID(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + cvnfcCustomization.setModelInstanceName(cvfcTemplate.getName()); + cvnfcCustomization.setModelInvariantUUID(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID)); + cvnfcCustomization.setModelName(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME)); + cvnfcCustomization.setModelUUID(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + + cvnfcCustomization.setModelVersion( + testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + cvnfcCustomization.setDescription( + testNull(cvfcTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + cvnfcCustomization.setToscaNodeType(testNull(cvfcTemplate.getType())); + + if(existingVnfcCustomization != null){ + cvnfcCustomization.setVnfcCustomization(existingVnfcCustomization); + }else{ + cvnfcCustomization.setVnfcCustomization(vnfcCustomization); + } + + cvnfcCustomization.setNfcFunction(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_function")); + cvnfcCustomization.setNfcNamingCode(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(cvfcTemplate, "nfc_naming_code")); + cvnfcCustomization.setVfModuleCustomization(vfModuleCustomization); + cvnfcCustomization.setVnfResourceCustomization(vnfResource); + + cvnfcCustomizations.add(cvnfcCustomization); + existingCvnfcSet.add(cvnfcCustomization); + + //***************************************************************************************************************************************** + //* Extract Fabric Configuration + //***************************************************************************************************************************************** + + List<NodeTemplate> fabricConfigList = toscaResourceStructure.getSdcCsarHelper().getNodeTemplateBySdcType(vfTemplate, SdcTypes.CONFIGURATION); + + for(NodeTemplate fabricTemplate : fabricConfigList) { + + ConfigurationResource fabricConfig = null; + + ConfigurationResource existingConfig = findExistingConfiguration(service, fabricTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + + if(existingConfig == null){ + + fabricConfig = createFabricConfiguration(fabricTemplate, toscaResourceStructure); + + }else { + fabricConfig = existingConfig; + } + + VnfVfmoduleCvnfcConfigurationCustomization vnfVfmoduleCvnfcConfigurationCustomization = createVfCnvfConfigCustomization(fabricTemplate, toscaResourceStructure, + vnfResource, vfModuleCustomization, cvnfcCustomization, fabricConfig, vfTemplate, vfModuleMemberName); + vnfVfmoduleCvnfcConfigurationCustomizations.add(vnfVfmoduleCvnfcConfigurationCustomization); + } + cvnfcCustomization.setVnfVfmoduleCvnfcConfigurationCustomization(vnfVfmoduleCvnfcConfigurationCustomizations); + } + + } + + } + } + vfModuleCustomization.setCvnfcCustomization(cvnfcCustomizations); + vfModuleCustomization.setVnfVfmoduleCvnfcConfigurationCustomization(vnfVfmoduleCvnfcConfigurationCustomizations); + + return vfModuleCustomization; + } + + protected VnfVfmoduleCvnfcConfigurationCustomization createVfCnvfConfigCustomization(NodeTemplate fabricTemplate, ToscaResourceStructure toscaResourceStruct, + VnfResourceCustomization vnfResource, VfModuleCustomization vfModuleCustomization, CvnfcCustomization cvnfcCustomization, + ConfigurationResource configResource, NodeTemplate vfTemplate, String vfModuleMemberName) { + + Metadata fabricMetadata = fabricTemplate.getMetaData(); + + VnfVfmoduleCvnfcConfigurationCustomization vfModuleToCvnfc = new VnfVfmoduleCvnfcConfigurationCustomization(); + + vfModuleToCvnfc.setConfigurationResource(configResource); + vfModuleToCvnfc.setCvnfcCustomization(cvnfcCustomization); + vfModuleToCvnfc.setModelCustomizationUUID(fabricMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + vfModuleToCvnfc.setModelInstanceName(fabricTemplate.getName()); + vfModuleToCvnfc.setVfModuleCustomization(vfModuleCustomization); + vfModuleToCvnfc.setVnfResourceCustomization(vnfResource); + + List<Policy> policyList = toscaResourceStruct.getSdcCsarHelper().getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(vfTemplate, "org.openecomp.policies.External"); + + if(policyList != null){ + for(Policy policy : policyList){ + + for(String policyCvfcTarget : policy.getTargets()){ + + if(policyCvfcTarget.equalsIgnoreCase(vfModuleMemberName)){ + + Map<String, Object> propMap = policy.getPolicyProperties(); + + if(propMap.get("type").toString().equalsIgnoreCase("Fabric Policy")){ + vfModuleToCvnfc.setPolicyName(propMap.get("name").toString()); + } + } + } + } + } + + vfModuleToCvnfc.setConfigurationFunction(toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "function")); + vfModuleToCvnfc.setConfigurationRole(toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "role")); + vfModuleToCvnfc.setConfigurationType(toscaResourceStruct.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(fabricTemplate, "type")); + + return vfModuleToCvnfc; + } + + protected ConfigurationResource findExistingConfiguration(Service service, String modelUUID) { + ConfigurationResource configResource = null; + for(ConfigurationResourceCustomization configurationResourceCustom : service.getConfigurationCustomizations()){ + if (configurationResourceCustom.getConfigurationResource() != null + && configurationResourceCustom.getConfigurationResource().getModelUUID().equals(modelUUID)) { + configResource = configurationResourceCustom.getConfigurationResource(); + } + } + if(configResource==null) + configResource = configRepo.findResourceByModelUUID(modelUUID); + + return configResource; + } + + protected VfModuleCustomization findExistingVfModuleCustomization(VnfResourceCustomization vnfResource, + String vfModuleModelCustomizationUUID) { + VfModuleCustomization vfModuleCustomization = null; + for(VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()){ + if(vfModuleCustom.getModelCustomizationUUID().equalsIgnoreCase(vfModuleModelCustomizationUUID)){ + vfModuleCustomization = vfModuleCustom; + } + } + if(vfModuleCustomization==null) + vfModuleCustomization = vfModuleCustomizationRepo + .findByModelCustomizationUUID(vfModuleModelCustomizationUUID); + + return vfModuleCustomization; + } + + protected VfModule findExistingVfModule(VnfResourceCustomization vnfResource, String modelUUID) { + VfModule vfModule = null; + for(VfModuleCustomization vfModuleCustom : vnfResource.getVfModuleCustomizations()){ + if(vfModuleCustom.getVfModule() != null && vfModuleCustom.getVfModule().getModelUUID().equals(modelUUID)){ + vfModule = vfModuleCustom.getVfModule(); + } + } + if(vfModule==null) + vfModule = vfModuleRepo.findByModelUUID(modelUUID); + + return vfModule; + } + + protected VfModuleCustomization createVfModuleCustomization(Group group, + ToscaResourceStructure toscaResourceStructure, VfModule vfModule, IVfModuleData vfModuleData) { + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + + vfModuleCustomization.setModelCustomizationUUID(vfModuleData.getVfModuleModelCustomizationUUID()); + + vfModuleCustomization.setVfModule(vfModule); + + String initialCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT); + if (initialCount != null && initialCount.length() > 0) { + vfModuleCustomization.setInitialCount(Integer.valueOf(initialCount)); + } + + vfModuleCustomization.setInitialCount(Integer.valueOf(toscaResourceStructure.getSdcCsarHelper() + .getGroupPropertyLeafValue(group, SdcPropertyNames.PROPERTY_NAME_INITIALCOUNT))); + + String availabilityZoneCount = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT); + if (availabilityZoneCount != null && availabilityZoneCount.length() > 0) { + vfModuleCustomization.setAvailabilityZoneCount(Integer.valueOf(availabilityZoneCount)); + } + + vfModuleCustomization.setLabel(toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_VFMODULELABEL)); + + String maxInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_MAXVFMODULEINSTANCES); + if (maxInstances != null && maxInstances.length() > 0) { + vfModuleCustomization.setMaxInstances(Integer.valueOf(maxInstances)); + } + + String minInstances = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_MINVFMODULEINSTANCES); + if (minInstances != null && minInstances.length() > 0) { + vfModuleCustomization.setMinInstances(Integer.valueOf(minInstances)); + } + return vfModuleCustomization; + } + + protected VfModule createVfModule(Group group, ToscaResourceStructure toscaResourceStructure, + IVfModuleData vfModuleData, Metadata vfMetadata) { + VfModule vfModule = new VfModule(); + String vfModuleModelUUID = vfModuleData.getVfModuleModelUUID(); + + if(vfModuleModelUUID == null) { + vfModuleModelUUID = testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)); + } else if (vfModuleModelUUID.indexOf('.') > -1) { + vfModuleModelUUID = vfModuleModelUUID.substring(0, vfModuleModelUUID.indexOf('.')); + } + + vfModule.setModelInvariantUUID(testNull(toscaResourceStructure.getSdcCsarHelper() + .getMetadataPropertyValue(vfMetadata, SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID))); + vfModule.setModelName(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME))); + vfModule.setModelUUID(vfModuleModelUUID); + vfModule.setModelVersion(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION))); + vfModule.setDescription(testNull(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + + String vfModuleType = toscaResourceStructure.getSdcCsarHelper().getGroupPropertyLeafValue(group, + SdcPropertyNames.PROPERTY_NAME_VFMODULETYPE); + if (vfModuleType != null && "Base".equalsIgnoreCase(vfModuleType)) { + vfModule.setIsBase(true); + } else { + vfModule.setIsBase(false); + } + return vfModule; + } + + protected void setHeatInformationForVfModule(ToscaResourceStructure toscaResourceStructure, + VfResourceStructure vfResourceStructure, VfModule vfModule, VfModuleCustomization vfModuleCustomization, + Metadata vfMetadata) { + + Optional<VfModuleStructure> matchingObject = vfResourceStructure.getVfModuleStructure().stream() + .filter(vfModuleStruct -> vfModuleStruct.getVfModuleMetadata().getVfModuleModelUUID() + .equalsIgnoreCase(toscaResourceStructure.getSdcCsarHelper().getMetadataPropertyValue(vfMetadata, + SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID))) + .findFirst(); + + if (matchingObject.isPresent()) { + List<HeatFiles> heatFilesList = new ArrayList<>(); + List<HeatTemplate> volumeHeatChildTemplates = new ArrayList<HeatTemplate>(); + List<HeatTemplate> heatChildTemplates = new ArrayList<HeatTemplate>(); + HeatTemplate parentHeatTemplate = new HeatTemplate(); + String parentArtifactType = null; + Set<String> artifacts = new HashSet<>(matchingObject.get().getVfModuleMetadata().getArtifacts()); + for (VfModuleArtifact vfModuleArtifact : vfResourceStructure.getArtifactsMapByUUID().values()) { + + List<HeatTemplate> childNestedHeatTemplates = new ArrayList<HeatTemplate>(); + + if (artifacts.contains(vfModuleArtifact.getArtifactInfo().getArtifactUUID())) { + checkVfModuleArtifactType(vfModule, vfModuleCustomization, heatFilesList, vfModuleArtifact, + childNestedHeatTemplates, parentHeatTemplate, vfResourceStructure); + } + + if(vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)){ + parentArtifactType = identifyParentOfNestedTemplate(matchingObject.get(), vfModuleArtifact); + + if(!childNestedHeatTemplates.isEmpty()){ + + if (parentArtifactType != null && parentArtifactType.equalsIgnoreCase(ASDCConfiguration.HEAT_VOL)) { + volumeHeatChildTemplates.add(childNestedHeatTemplates.get(0)); + } else { + heatChildTemplates.add(childNestedHeatTemplates.get(0)); + } + } + } + + } + if(!heatFilesList.isEmpty()){ + vfModule.setHeatFiles(heatFilesList); + } + + + // Set all Child Templates related to HEAT_VOLUME + if(!volumeHeatChildTemplates.isEmpty()){ + if(vfModule.getVolumeHeatTemplate() != null){ + vfModule.getVolumeHeatTemplate().setChildTemplates(volumeHeatChildTemplates); + }else{ + logger.debug("VolumeHeatTemplate not set in setHeatInformationForVfModule()"); + } + } + + // Set all Child Templates related to HEAT + if(!heatChildTemplates.isEmpty()){ + if(vfModule.getModuleHeatTemplate() != null){ + vfModule.getModuleHeatTemplate().setChildTemplates(heatChildTemplates); + }else{ + logger.debug("ModuleHeatTemplate not set in setHeatInformationForVfModule()"); + } + } + } + } + + protected void checkVfModuleArtifactType(VfModule vfModule, VfModuleCustomization vfModuleCustomization, + List<HeatFiles> heatFilesList, VfModuleArtifact vfModuleArtifact, List<HeatTemplate> nestedHeatTemplates, + HeatTemplate parentHeatTemplate, VfResourceStructure vfResourceStructure) { + if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT)) { + vfModuleArtifact.incrementDeployedInDB(); + vfModule.setModuleHeatTemplate(vfModuleArtifact.getHeatTemplate()); + } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_VOL)) { + vfModule.setVolumeHeatTemplate(vfModuleArtifact.getHeatTemplate()); + VfModuleArtifact volVfModuleArtifact = this.getHeatEnvArtifactFromGeneratedArtifact(vfResourceStructure, vfModuleArtifact); + vfModuleCustomization.setVolumeHeatEnv(volVfModuleArtifact.getHeatEnvironment()); + vfModuleArtifact.incrementDeployedInDB(); + } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ENV)) { + if(vfModuleArtifact.getHeatEnvironment().getName().contains("volume")) { + vfModuleCustomization.setVolumeHeatEnv(vfModuleArtifact.getHeatEnvironment()); + } else { + vfModuleCustomization.setHeatEnvironment(vfModuleArtifact.getHeatEnvironment()); + } + vfModuleArtifact.incrementDeployedInDB(); + } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_ARTIFACT)) { + heatFilesList.add(vfModuleArtifact.getHeatFiles()); + vfModuleArtifact.incrementDeployedInDB(); + } else if (vfModuleArtifact.getArtifactInfo().getArtifactType().equals(ASDCConfiguration.HEAT_NESTED)) { + nestedHeatTemplates.add(vfModuleArtifact.getHeatTemplate()); + vfModuleArtifact.incrementDeployedInDB(); + } + } + + protected VnfResourceCustomization createVnfResource(NodeTemplate vfNodeTemplate, + ToscaResourceStructure toscaResourceStructure, Service service) { + VnfResourceCustomization vnfResourceCustomization = vnfCustomizationRepo.findOneByModelCustomizationUUID( + vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + if(vnfResourceCustomization == null){ + VnfResource vnfResource = findExistingVnfResource(service, + vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + + if(vnfResource==null) + vnfResource=createVnfResource(vfNodeTemplate); + + vnfResourceCustomization = createVnfResourceCustomization(vfNodeTemplate, toscaResourceStructure, + vnfResource); + vnfResourceCustomization.setVnfResources(vnfResource); + vnfResource.getVnfResourceCustomizations().add(vnfResourceCustomization); + + // Fetch VNFC Instance Group Info + List<Group> groupList = toscaResourceStructure.getSdcCsarHelper() + .getGroupsOfOriginOfNodeTemplateByToscaGroupType(vfNodeTemplate, + "org.openecomp.groups.VfcInstanceGroup"); + + for (Group group : groupList) { + + VnfcInstanceGroupCustomization vnfcInstanceGroupCustomization = createVNFCInstanceGroup(vfNodeTemplate, group, vnfResourceCustomization, toscaResourceStructure); + + vnfcInstanceGroupCustomizationRepo.saveAndFlush(vnfcInstanceGroupCustomization); + } + } + return vnfResourceCustomization; + } + + protected VnfResource findExistingVnfResource(Service service, String modelUUID) { + VnfResource vnfResource = null; + for(VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()){ + if (vnfResourceCustom.getVnfResources() != null + && vnfResourceCustom.getVnfResources().getModelUUID().equals(modelUUID)) { + vnfResource = vnfResourceCustom.getVnfResources(); + } + } + if(vnfResource==null) + vnfResource = vnfRepo.findResourceByModelUUID(modelUUID); + + return vnfResource; + } + + protected VnfResourceCustomization createVnfResourceCustomization(NodeTemplate vfNodeTemplate, + ToscaResourceStructure toscaResourceStructure, VnfResource vnfResource) { + VnfResourceCustomization vnfResourceCustomization = new VnfResourceCustomization(); + vnfResourceCustomization.setModelCustomizationUUID( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + vnfResourceCustomization.setModelInstanceName(vfNodeTemplate.getName()); + + vnfResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); + vnfResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, "nf_naming_code"))); + vnfResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE))); + vnfResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE))); + + vnfResourceCustomization.setMultiStageDesign(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, MULTI_STAGE_DESIGN)); + + vnfResourceCustomization.setBlueprintName(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_NAME))); + + vnfResourceCustomization.setBlueprintVersion(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(vfNodeTemplate, SDNC_MODEL_VERSION))); + + vnfResourceCustomization.setVnfResources(vnfResource); + vnfResourceCustomization.setAvailabilityZoneMaxCount(Integer.getInteger( + vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_AVAILABILITYZONECOUNT))); + + CapabilityAssignments vnfCustomizationCapability = toscaResourceStructure.getSdcCsarHelper() + .getCapabilitiesOf(vfNodeTemplate); + + if (vnfCustomizationCapability != null) { + CapabilityAssignment capAssign = vnfCustomizationCapability.getCapabilityByName(SCALABLE); + + if (capAssign != null) { + vnfResourceCustomization.setMinInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper() + .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); + vnfResourceCustomization.setMaxInstances(Integer.getInteger(toscaResourceStructure.getSdcCsarHelper() + .getCapabilityPropertyLeafValue(capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); + } + + } + + toscaResourceStructure.setCatalogVnfResourceCustomization(vnfResourceCustomization); + + return vnfResourceCustomization; + } + + protected VnfResource createVnfResource(NodeTemplate vfNodeTemplate) { + VnfResource vnfResource = new VnfResource(); + vnfResource.setModelInvariantUUID( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + vnfResource.setModelName(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + vnfResource.setModelUUID(testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + + vnfResource.setModelVersion( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + vnfResource.setDescription( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION))); + vnfResource.setOrchestrationMode(HEAT); + vnfResource.setToscaNodeType(testNull(vfNodeTemplate.getType())); + vnfResource.setAicVersionMax( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); + vnfResource.setAicVersionMin( + testNull(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); + vnfResource.setCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CATEGORY)); + vnfResource.setSubCategory(vfNodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY)); + + return vnfResource; + } + + protected AllottedResourceCustomization createAllottedResource(NodeTemplate nodeTemplate, + ToscaResourceStructure toscaResourceStructure, Service service) { + AllottedResourceCustomization allottedResourceCustomization = allottedCustomizationRepo + .findOneByModelCustomizationUUID( + nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)); + + if(allottedResourceCustomization == null){ + AllottedResource allottedResource = findExistingAllottedResource(service, + nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID)); + + if(allottedResource==null) + allottedResource=createAR(nodeTemplate); + + toscaResourceStructure.setAllottedResource(allottedResource); + allottedResourceCustomization = createAllottedResourceCustomization(nodeTemplate, toscaResourceStructure); + allottedResourceCustomization.setAllottedResource(allottedResource); + allottedResource.getAllotedResourceCustomization().add(allottedResourceCustomization); + } + return allottedResourceCustomization; + } + + protected AllottedResource findExistingAllottedResource(Service service, String modelUUID) { + AllottedResource allottedResource = null; + for(AllottedResourceCustomization allottedResourceCustom : service.getAllottedCustomizations()){ + if (allottedResourceCustom.getAllottedResource() != null + && allottedResourceCustom.getAllottedResource().getModelUUID().equals(modelUUID)) { + allottedResource = allottedResourceCustom.getAllottedResource(); + } + } + if(allottedResource==null) + allottedResource = allottedRepo.findResourceByModelUUID(modelUUID); + + return allottedResource; + } + + protected AllottedResourceCustomization createAllottedResourceCustomization(NodeTemplate nodeTemplate, + ToscaResourceStructure toscaResourceStructure) { + AllottedResourceCustomization allottedResourceCustomization = new AllottedResourceCustomization(); + allottedResourceCustomization.setModelCustomizationUUID( + testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID))); + allottedResourceCustomization.setModelInstanceName(nodeTemplate.getName()); + + + allottedResourceCustomization.setNfFunction(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFFUNCTION))); + allottedResourceCustomization.setNfNamingCode(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(nodeTemplate, "nf_naming_code"))); + allottedResourceCustomization.setNfRole(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFROLE))); + allottedResourceCustomization.setNfType(testNull(toscaResourceStructure.getSdcCsarHelper() + .getNodeTemplatePropertyLeafValue(nodeTemplate, SdcPropertyNames.PROPERTY_NAME_NFTYPE))); + + List<NodeTemplate> vfcNodes = toscaResourceStructure.getSdcCsarHelper().getVfcListByVf(allottedResourceCustomization.getModelCustomizationUUID()); + + if(vfcNodes != null){ + for(NodeTemplate vfcNode : vfcNodes){ + + allottedResourceCustomization.setProvidingServiceModelUUID(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_uuid")); + allottedResourceCustomization.setProvidingServiceModelInvariantUUID(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_invariant_uuid")); + allottedResourceCustomization.setProvidingServiceModelName(toscaResourceStructure.getSdcCsarHelper().getNodeTemplatePropertyLeafValue(vfcNode, "providing_service_name")); + } + } + + + CapabilityAssignments arCustomizationCapability = toscaResourceStructure.getSdcCsarHelper() + .getCapabilitiesOf(nodeTemplate); + + if (arCustomizationCapability != null) { + CapabilityAssignment capAssign = arCustomizationCapability.getCapabilityByName(SCALABLE); + + if (capAssign != null) { + allottedResourceCustomization.setMinInstances( + Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue( + capAssign, SdcPropertyNames.PROPERTY_NAME_MININSTANCES))); + allottedResourceCustomization.setMaxInstances( + Integer.getInteger(toscaResourceStructure.getSdcCsarHelper().getCapabilityPropertyLeafValue( + capAssign, SdcPropertyNames.PROPERTY_NAME_MAXINSTANCES))); + } + } + return allottedResourceCustomization; + } + + protected AllottedResource createAR(NodeTemplate nodeTemplate) { + AllottedResource allottedResource = new AllottedResource(); + allottedResource + .setModelUUID(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_UUID))); + allottedResource.setModelInvariantUUID( + testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_INVARIANTUUID))); + allottedResource + .setModelName(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME))); + allottedResource + .setModelVersion(testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_VERSION))); + allottedResource.setToscaNodeType(testNull(nodeTemplate.getType())); + allottedResource.setSubcategory( + testNull(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_SUBCATEGORY))); + allottedResource + .setDescription(nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_DESCRIPTION)); + return allottedResource; + } + + protected Set<HeatTemplateParam> extractHeatTemplateParameters(String yamlFile, String artifactUUID) { + // Scan the payload downloadResult and extract the HeatTemplate + // parameters + YamlEditor yamlEditor = new YamlEditor(yamlFile.getBytes()); + return yamlEditor.getParameterList(artifactUUID); + } + + protected String testNull(Object object) { + + if (object == null) { + return null; + } else if (object.equals("NULL")) { + return null; + } else if (object instanceof Integer) { + return object.toString(); + } else if (object instanceof String) { + return (String) object; + } else { + return "Type not recognized"; + } + } + + protected static String identifyParentOfNestedTemplate(VfModuleStructure vfModuleStructure, + VfModuleArtifact heatNestedArtifact) { + + if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT) != null && vfModuleStructure + .getArtifactsMap().get(ASDCConfiguration.HEAT).get(0).getArtifactInfo().getRelatedArtifacts() != null) { + for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT).get(0) + .getArtifactInfo().getRelatedArtifacts()) { + if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { + return ASDCConfiguration.HEAT; + } + + } + } + + if (vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) != null + && vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL).get(0).getArtifactInfo() + .getRelatedArtifacts() != null) { + for (IArtifactInfo unknownArtifact : vfModuleStructure.getArtifactsMap().get(ASDCConfiguration.HEAT_VOL) + .get(0).getArtifactInfo().getRelatedArtifacts()) { + if (heatNestedArtifact.getArtifactInfo().getArtifactUUID().equals(unknownArtifact.getArtifactUUID())) { + return ASDCConfiguration.HEAT_VOL; + } + + } + } + + // Does not belong to anything + return null; + + } + + protected static String createVNFName(VfResourceStructure vfResourceStructure) { + + return vfResourceStructure.getNotification().getServiceName() + "/" + + vfResourceStructure.getResourceInstance().getResourceInstanceName(); + } + + protected static String createVfModuleName(VfModuleStructure vfModuleStructure) { + + return createVNFName(vfModuleStructure.getParentVfResource()) + "::" + + vfModuleStructure.getVfModuleMetadata().getVfModuleModelName(); + } + + protected String getPropertyInput(String propertyName){ + + String inputName = new String(); + + if (propertyName != null) { + int getInputIndex = propertyName.indexOf("{get_input="); + if (getInputIndex > -1) { + inputName = propertyName.substring(getInputIndex+11, propertyName.length()-1); + } + } + + return inputName; + } + + + protected static Timestamp getCurrentTimeStamp() { + + return new Timestamp(new Date().getTime()); + } } + diff --git a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java index c0c66123eb..85ecaaa3ea 100644 --- a/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java +++ b/asdc-controller/src/test/java/org/onap/so/asdc/client/ASDCControllerITTest.java @@ -31,9 +31,12 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.UUID; + import javax.persistence.EntityNotFoundException; + import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; @@ -297,6 +300,7 @@ public class ASDCControllerITTest extends BaseTest { * Testing with the service-Svc140-VF-csar.csar. */ @Test + @Ignore public void treatNotification_ValidVnfResource_ExpectedOutput() { /** diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java index 1c1d6b73fd..39a209efa8 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/bpmn/common/DelegateExecutionImpl.java @@ -1,22 +1,22 @@ /*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * +* ============LICENSE_START======================================================= +* ONAP - SO +* ================================================================================ +* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +* ================================================================================ +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* * http://www.apache.org/licenses/LICENSE-2.0 - * +* * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============LICENSE_END========================================================= +*/ package org.onap.so.bpmn.common; @@ -31,92 +31,107 @@ import org.onap.so.bpmn.common.exceptions.RequiredExecutionVariableExeception; import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; + public class DelegateExecutionImpl implements BuildingBlockExecution, Serializable { - private final Map<String, Serializable> seedMap; - private transient DelegateExecution execution; - private static final String INVALID_INPUT_MISSING = "Expected variable of \"%s\" not found in execution"; - private static final String INVALID_INPUT_CLASS_CAST = "Expected variable of \"%s\" was the wrong object type in the execution"; - - private static final String MISSING_MSG = "Execution variable \"gBBInput\" cannot be null when executing building blocks"; - private static final String MALFORMED_MSG = "Execution variable \"gBBInput\" must contain an element of type GeneralBuildingBlock"; - - public DelegateExecutionImpl(Map<String, Serializable> seedMap) { - this.seedMap = seedMap; - } - - public DelegateExecutionImpl(DelegateExecution execution) { - this.seedMap = new HashMap<>(); - execution.getVariables().forEach((key, value) -> { - if (value instanceof Serializable) { - seedMap.put(key, (Serializable)value); - } - }); - /* must occur for junit tests to work */ - this.execution = execution; - } - @Override - public GeneralBuildingBlock getGeneralBuildingBlock() { - try { - GeneralBuildingBlock generalBuildingBlock = (GeneralBuildingBlock) execution.getVariable("gBBInput"); - - if (generalBuildingBlock == null) { - throw new MissingBuildingBlockInputException(MISSING_MSG); - } - - return generalBuildingBlock; - } catch (ClassCastException e) { - throw new MalformedBuildingBlockInputException(MALFORMED_MSG, e); - } - } - - @Override - public <T> T getVariable(String key) { - return this.get(key); - } - - @Override - public <T> T getRequiredVariable(String key) throws RequiredExecutionVariableExeception { - final T result; - - result = this.get(key); - if (result == null) { - throw new RequiredExecutionVariableExeception(String.format(INVALID_INPUT_MISSING, key)); - - } - return result; - } - - @Override - public void setVariable(String key, Serializable value) { - this.execution.setVariable(key, value); - } - - @Override - public Map<ResourceKey, String> getLookupMap() { - return this.get("lookupKeyMap"); - } - - @Override - public String getFlowToBeCalled() { - return this.get("flowToBeCalled"); - } - public DelegateExecution getDelegateExecution() { - return this.execution; - } - - public void setDelegateExecution(DelegateExecution execution) { - this.execution = execution; - this.seedMap.forEach((key, value) -> { - if (!execution.hasVariable(key)) { - execution.setVariable(key, value); - } - }); - } - - protected <T> T get(String key) { - final Object value = this.execution.getVariable(key); - - return (T)value; - } + private static final long serialVersionUID = 5559067662634919395L; + + @JsonProperty + private final Map<String, Serializable> seedMap; + + private transient DelegateExecution execution; + private static final String INVALID_INPUT_MISSING = "Expected variable of \"%s\" not found in execution"; + + private static final String MISSING_MSG = + "Execution variable \"gBBInput\" cannot be null when executing building blocks"; + private static final String MALFORMED_MSG = + "Execution variable \"gBBInput\" must contain an element of type GeneralBuildingBlock"; + + public DelegateExecutionImpl(final Map<String, Serializable> seedMap) { + this.seedMap = seedMap; + } + + public DelegateExecutionImpl(final DelegateExecution execution) { + this.seedMap = new HashMap<>(); + execution.getVariables().forEach((key, value) -> { + if (value instanceof Serializable) { + seedMap.put(key, (Serializable) value); + } + }); + /* must occur for junit tests to work */ + this.execution = execution; + } + + @JsonIgnore + @Override + public GeneralBuildingBlock getGeneralBuildingBlock() { + try { + final GeneralBuildingBlock generalBuildingBlock = (GeneralBuildingBlock) execution.getVariable("gBBInput"); + + if (generalBuildingBlock == null) { + throw new MissingBuildingBlockInputException(MISSING_MSG); + } + + return generalBuildingBlock; + } catch (final ClassCastException e) { + throw new MalformedBuildingBlockInputException(MALFORMED_MSG, e); + } + } + + @Override + public <T> T getVariable(final String key) { + return this.get(key); + } + + @Override + public <T> T getRequiredVariable(final String key) throws RequiredExecutionVariableExeception { + final T result; + + result = this.get(key); + if (result == null) { + throw new RequiredExecutionVariableExeception(String.format(INVALID_INPUT_MISSING, key)); + + } + return result; + } + + @Override + public void setVariable(final String key, final Serializable value) { + this.execution.setVariable(key, value); + } + + @JsonIgnore + @Override + public Map<ResourceKey, String> getLookupMap() { + return this.get("lookupKeyMap"); + } + + @JsonIgnore + @Override + public String getFlowToBeCalled() { + return this.get("flowToBeCalled"); + } + + @JsonIgnore + public DelegateExecution getDelegateExecution() { + return this.execution; + } + + public void setDelegateExecution(final DelegateExecution execution) { + this.execution = execution; + this.seedMap.forEach((key, value) -> { + if (!execution.hasVariable(key)) { + execution.setVariable(key, value); + } + }); + } + + @SuppressWarnings("unchecked") + protected <T> T get(final String key) { + final Object value = this.execution.getVariable(key); + return (T) value; + } + } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DelegateExecutionImplTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DelegateExecutionImplTest.java index 32a18d5a7a..a30aadc1f8 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DelegateExecutionImplTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/onap/so/bpmn/common/DelegateExecutionImplTest.java @@ -20,19 +20,15 @@ package org.onap.so.bpmn.common; -import static org.hamcrest.CoreMatchers.hasItems; -import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; -import static org.mockito.ArgumentMatchers.contains; +import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import java.io.Serializable; -import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -46,101 +42,115 @@ import org.onap.so.bpmn.common.exceptions.MissingBuildingBlockInputException; import org.onap.so.bpmn.common.exceptions.RequiredExecutionVariableExeception; import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + public class DelegateExecutionImplTest { - @Rule - public ExpectedException thrown= ExpectedException.none(); - - - @Test - public void getVariable() throws RequiredExecutionVariableExeception { - Map<String, Serializable> map = new HashMap<>(); - map.put("var1", "value1"); - map.put("var2", "value2"); - map.put("list1", (Serializable)Arrays.asList("value1", "value2")); - DelegateExecutionImpl impl = create(map); - - assertEquals("value1", impl.getVariable("var1")); - assertEquals("value2", impl.getRequiredVariable("var2")); - assertThat(impl.getVariable("list1"), IsIterableContainingInOrder.contains("value1", "value2")); - - } - - - @Test - public void getRequiredVariableNotFound() throws RequiredExecutionVariableExeception { - DelegateExecutionImpl impl = create(); - - thrown.expect(RequiredExecutionVariableExeception.class); - impl.getRequiredVariable("var1"); - } - - - @Test - public void setVariable() { - DelegateExecutionImpl impl = create(); - impl.setVariable("var1", "value1"); - - assertEquals("value1", impl.get("var1")); - } - - @Test - public void getGeneralBuildingBlock() { - GeneralBuildingBlock gBB = mock(GeneralBuildingBlock.class); - Map<String, Serializable> map = new HashMap<>(); - map.put("gBBInput", gBB); - DelegateExecutionImpl impl = create(map); - - assertEquals(gBB, impl.getGeneralBuildingBlock()); - } - - @Test - public void getGeneralBuildingBlockNotFound() { - - DelegateExecutionImpl impl = create(); - - thrown.expect(MissingBuildingBlockInputException.class); - impl.getGeneralBuildingBlock(); - } - - @Test - public void getGeneralBuildingBlockCastException() { - Map<String, Serializable> map = new HashMap<>(); - map.put("gBBInput", new DelegateExecutionFake()); - DelegateExecutionImpl impl = create(map); - - thrown.expect(MalformedBuildingBlockInputException.class); - impl.getGeneralBuildingBlock(); - } - - @Test - public void getDelegateExecution() { - DelegateExecutionImpl impl = create(); - - assertNotNull(impl.getDelegateExecution()); - } - - @Test - public void getLookupMap() { - Map<String, Serializable> lookup = new HashMap<>(); - Map<String, Serializable> map = new HashMap<>(); - map.put("lookupKeyMap", (Serializable) lookup); - DelegateExecutionImpl impl = create(map); - - assertEquals(lookup, impl.getLookupMap()); - } - - private DelegateExecutionImpl create() { - return create(new HashMap<String, Serializable>()); - } - - private DelegateExecutionImpl create(Map<String, Serializable> map) { - DelegateExecutionFake fake = new DelegateExecutionFake(); - - for (Entry<String, Serializable> entry : map.entrySet()) { - fake.setVariable(entry.getKey(), entry.getValue()); - } - return new DelegateExecutionImpl(fake); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); + + + @Test + public void getVariable() throws RequiredExecutionVariableExeception { + final Map<String, Serializable> map = new HashMap<>(); + map.put("var1", "value1"); + map.put("var2", "value2"); + map.put("list1", (Serializable) Arrays.asList("value1", "value2")); + final DelegateExecutionImpl impl = create(map); + + assertEquals("value1", impl.getVariable("var1")); + assertEquals("value2", impl.getRequiredVariable("var2")); + assertThat(impl.getVariable("list1"), IsIterableContainingInOrder.contains("value1", "value2")); + + } + + + @Test + public void getRequiredVariableNotFound() throws RequiredExecutionVariableExeception { + final DelegateExecutionImpl impl = create(); + + thrown.expect(RequiredExecutionVariableExeception.class); + impl.getRequiredVariable("var1"); + } + + + @Test + public void setVariable() { + final DelegateExecutionImpl impl = create(); + impl.setVariable("var1", "value1"); + + assertEquals("value1", impl.get("var1")); + } + + @Test + public void getGeneralBuildingBlock() { + final GeneralBuildingBlock gBB = mock(GeneralBuildingBlock.class); + final Map<String, Serializable> map = new HashMap<>(); + map.put("gBBInput", gBB); + final DelegateExecutionImpl impl = create(map); + + assertEquals(gBB, impl.getGeneralBuildingBlock()); + } + + @Test + public void getGeneralBuildingBlockNotFound() { + final DelegateExecutionImpl impl = create(); + thrown.expect(MissingBuildingBlockInputException.class); + impl.getGeneralBuildingBlock(); + } + + @Test + public void getGeneralBuildingBlockCastException() { + final Map<String, Serializable> map = new HashMap<>(); + map.put("gBBInput", new DelegateExecutionFake()); + final DelegateExecutionImpl impl = create(map); + + thrown.expect(MalformedBuildingBlockInputException.class); + impl.getGeneralBuildingBlock(); + } + + @Test + public void getDelegateExecution() { + final DelegateExecutionImpl impl = create(); + + assertNotNull(impl.getDelegateExecution()); + } + + @Test + public void getLookupMap() { + final Map<String, Serializable> lookup = new HashMap<>(); + final Map<String, Serializable> map = new HashMap<>(); + map.put("lookupKeyMap", (Serializable) lookup); + final DelegateExecutionImpl impl = create(map); + + assertEquals(lookup, impl.getLookupMap()); + } + + @Test + public void testDelegateExecutionImpl_serializeDelegateExecutionImplObject_shouldNotThrowAnyExceptionWhenSerializing() { + final DelegateExecutionImpl objectUnderTest = create(); + + try { + final ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.writeValueAsString(objectUnderTest); + } catch (final JsonProcessingException e) { + fail("Should be possible to serialize DelegateExecutionImpl object"); + } + + } + + private DelegateExecutionImpl create() { + return create(new HashMap<String, Serializable>()); + } + + private DelegateExecutionImpl create(final Map<String, Serializable> map) { + final DelegateExecutionFake fake = new DelegateExecutionFake(); + + for (final Entry<String, Serializable> entry : map.entrySet()) { + fake.setVariable(entry.getKey(), entry.getValue()); + } + return new DelegateExecutionImpl(fake); + } } diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java index b11e2caafa..7b86756afa 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapper.java @@ -21,6 +21,7 @@ package org.onap.so.client.sdnc.mapper; import java.net.URI; +import java.util.UUID; import org.onap.sdnc.northbound.client.model.GenericResourceApiConfigurationinformationConfigurationInformation; import org.onap.sdnc.northbound.client.model.GenericResourceApiGcTopologyOperationInformation; @@ -52,9 +53,13 @@ public class GCTopologyOperationRequestMapper { Configuration vnrConfiguration, GenericVnf voiceVnf, String sdncReqId,URI callbackUri) { + String msoRequestId = UUID.randomUUID().toString(); + if (requestContext != null && requestContext.getMsoRequestId() != null) { + msoRequestId = requestContext.getMsoRequestId(); + } GenericResourceApiGcTopologyOperationInformation req = new GenericResourceApiGcTopologyOperationInformation(); GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId,callbackUri.toString()); - GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(sdncReqId, reqAction); + GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, reqAction); GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, false); GenericResourceApiConfigurationinformationConfigurationInformation configurationInformation = generalTopologyObjectMapper.buildConfigurationInformation(vnrConfiguration,true); GenericResourceApiGcrequestinputGcRequestInput gcRequestInput = generalTopologyObjectMapper.buildGcRequestInformation(voiceVnf,null); @@ -74,11 +79,15 @@ public class GCTopologyOperationRequestMapper { RequestContext requestContext, Configuration vnrConfiguration, String sdncReqId, URI callbackUri) { + String msoRequestId = null; + if (requestContext != null) { + msoRequestId = requestContext.getMsoRequestId(); + } GenericResourceApiGcTopologyOperationInformation req = new GenericResourceApiGcTopologyOperationInformation(); GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId,callbackUri.toString()); GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper - .buildGenericResourceApiRequestinformationRequestInformation(sdncReqId, + .buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, GenericResourceApiRequestActionEnumeration.DELETEGENERICCONFIGURATIONINSTANCE); GenericResourceApiServiceinformationServiceInformation serviceInformation = new GenericResourceApiServiceinformationServiceInformation(); serviceInformation.setServiceInstanceId(serviceInstance.getServiceInstanceId()); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java index b086b8a7ff..756e5b068e 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/GeneralTopologyObjectMapper.java @@ -60,10 +60,10 @@ public class GeneralTopologyObjectMapper { /* * Build GenericResourceApiRequestinformationRequestInformation */ - public GenericResourceApiRequestinformationRequestInformation buildGenericResourceApiRequestinformationRequestInformation(String sdncReqId, GenericResourceApiRequestActionEnumeration requestAction){ + public GenericResourceApiRequestinformationRequestInformation buildGenericResourceApiRequestinformationRequestInformation(String msoReqId, GenericResourceApiRequestActionEnumeration requestAction){ GenericResourceApiRequestinformationRequestInformation requestInformation = new GenericResourceApiRequestinformationRequestInformation(); - requestInformation.setRequestId(sdncReqId); + requestInformation.setRequestId(msoReqId); requestInformation.setRequestAction(requestAction); requestInformation.setSource("MSO"); return requestInformation; diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapper.java index 188a228e5d..aef7e9e044 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapper.java @@ -57,8 +57,12 @@ public class NetworkTopologyOperationRequestMapper { Customer customer, RequestContext requestContext, CloudRegion cloudRegion) { GenericResourceApiNetworkOperationInformation req = new GenericResourceApiNetworkOperationInformation(); String sdncReqId = UUID.randomUUID().toString(); + String msoRequestId = UUID.randomUUID().toString(); + if (requestContext != null && requestContext.getMsoRequestId() != null) { + msoRequestId = requestContext.getMsoRequestId(); + } GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId); - GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(sdncReqId, reqAction); + GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, reqAction); GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, true); GenericResourceApiNetworkinformationNetworkInformation networkInformation = generalTopologyObjectMapper.buildNetworkInformation(network); GenericResourceApiNetworkrequestinputNetworkRequestInput networkRequestInput = buildNetworkRequestInput(network, serviceInstance, cloudRegion); @@ -68,7 +72,7 @@ public class NetworkTopologyOperationRequestMapper { req.setServiceInformation(serviceInformation); req.setNetworkInformation(networkInformation); - if (requestContext.getUserParams() != null) { + if (requestContext != null && requestContext.getUserParams() != null) { for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) { GenericResourceApiParam networkInputParameters = new GenericResourceApiParam(); GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam(); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapper.java index 505466b22c..cdb4ab96aa 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapper.java @@ -49,9 +49,13 @@ public class ServiceTopologyOperationMapper{ SDNCSvcAction svcAction, GenericResourceApiRequestActionEnumeration resourceAction,ServiceInstance serviceInstance, Customer customer, RequestContext requestContext) { String sdncReqId = UUID.randomUUID().toString(); + String msoRequestId = UUID.randomUUID().toString(); + if (requestContext != null && requestContext.getMsoRequestId() != null) { + msoRequestId = requestContext.getMsoRequestId(); + } GenericResourceApiServiceOperationInformation servOpInput = new GenericResourceApiServiceOperationInformation(); GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper.buildSdncRequestHeader(svcAction, sdncReqId); - GenericResourceApiRequestinformationRequestInformation reqInfo = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(sdncReqId, resourceAction); + GenericResourceApiRequestinformationRequestInformation reqInfo = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, resourceAction); GenericResourceApiServiceinformationServiceInformation servInfo = generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, true); GenericResourceApiServicerequestinputServiceRequestInput servReqInfo = new GenericResourceApiServicerequestinputServiceRequestInput(); @@ -62,7 +66,7 @@ public class ServiceTopologyOperationMapper{ servOpInput.setServiceInformation(servInfo); servOpInput.setServiceRequestInput(servReqInfo); - if(requestContext.getUserParams()!=null){ + if(requestContext != null && requestContext.getUserParams()!=null){ for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) { GenericResourceApiServicerequestinputServiceRequestInput serviceRequestInput = new GenericResourceApiServicerequestinputServiceRequestInput(); serviceRequestInput.setServiceInstanceName(serviceInstance.getServiceInstanceName()); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java index b8c5fad41d..86c718d165 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapper.java @@ -96,8 +96,12 @@ public class VfModuleTopologyOperationRequestMapper { } String sdncReqId = UUID.randomUUID().toString(); + String msoRequestId = UUID.randomUUID().toString(); + if (requestContext != null && requestContext.getMsoRequestId() != null) { + msoRequestId = requestContext.getMsoRequestId(); + } - GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(sdncReqId, + GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper.buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, requestAction); GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper.buildServiceInformation(serviceInstance, requestContext, customer, includeModelInformation); GenericResourceApiVnfinformationVnfInformation vnfInformation = generalTopologyObjectMapper.buildVnfInformation(vnf, serviceInstance, includeModelInformation); diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapper.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapper.java index 7de393bb2f..85e5b85529 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapper.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapper.java @@ -59,11 +59,15 @@ public class VnfTopologyOperationRequestMapper { GenericResourceApiRequestActionEnumeration requestAction, GenericVnf vnf, ServiceInstance serviceInstance, Customer customer, CloudRegion cloudRegion, RequestContext requestContext, boolean homing) { String sdncReqId = UUID.randomUUID().toString(); + String msoRequestId = UUID.randomUUID().toString(); + if (requestContext != null && requestContext.getMsoRequestId() != null) { + msoRequestId = requestContext.getMsoRequestId(); + } GenericResourceApiVnfOperationInformation req = new GenericResourceApiVnfOperationInformation(); GenericResourceApiSdncrequestheaderSdncRequestHeader sdncRequestHeader = generalTopologyObjectMapper .buildSdncRequestHeader(svcAction, sdncReqId); GenericResourceApiRequestinformationRequestInformation requestInformation = generalTopologyObjectMapper - .buildGenericResourceApiRequestinformationRequestInformation(sdncReqId, requestAction); + .buildGenericResourceApiRequestinformationRequestInformation(msoRequestId, requestAction); GenericResourceApiServiceinformationServiceInformation serviceInformation = generalTopologyObjectMapper .buildServiceInformation(serviceInstance, requestContext, customer, true); GenericResourceApiVnfinformationVnfInformation vnfInformation = generalTopologyObjectMapper @@ -84,7 +88,7 @@ public class VnfTopologyOperationRequestMapper { req.setVnfInformation(vnfInformation); GenericResourceApiParam vnfInputParameters = new GenericResourceApiParam(); - if (requestContext.getUserParams() != null) { + if (requestContext != null && requestContext.getUserParams() != null) { for (Map.Entry<String, Object> entry : requestContext.getUserParams().entrySet()) { GenericResourceApiParamParam paramItem = new GenericResourceApiParamParam(); paramItem.setName(entry.getKey()); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java index 1bcc464fa0..d362996948 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/NetworkAdapterClientIT.java @@ -21,6 +21,7 @@ package org.onap.so.client.adapter.network; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; @@ -104,7 +105,7 @@ public class NetworkAdapterClientIT extends BaseIntegrationTest{ DeleteNetworkResponse mockResponse = new DeleteNetworkResponse(); mockResponse.setNetworkDeleted(true); - stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)) + stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200))); @@ -119,7 +120,7 @@ public class NetworkAdapterClientIT extends BaseIntegrationTest{ DeleteNetworkError mockResponse = new DeleteNetworkError(); mockResponse.setMessage("Error in delete network"); - stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)) + stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500))); @@ -136,7 +137,7 @@ public class NetworkAdapterClientIT extends BaseIntegrationTest{ RollbackNetworkResponse mockResponse = new RollbackNetworkResponse(); mockResponse.setNetworkRolledBack(true); - stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)) + stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200))); @@ -154,7 +155,7 @@ public class NetworkAdapterClientIT extends BaseIntegrationTest{ RollbackNetworkError mockResponse = new RollbackNetworkError(); mockResponse.setMessage("Error in rollback network"); - stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)) + stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_NETWORK_ID)) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500))); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java index 3387920d40..cb3d91b82a 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/VnfAdapterClientIT.java @@ -21,6 +21,7 @@ package org.onap.so.client.adapter.vnf; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; @@ -102,7 +103,7 @@ public class VnfAdapterClientIT extends BaseIntegrationTest{ RollbackVfModuleResponse mockResponse = new RollbackVfModuleResponse(); mockResponse.setVfModuleRolledback(true); stubFor( - post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID + "/rollback")) + delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID + "/rollback")) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200))); @@ -120,7 +121,7 @@ public class VnfAdapterClientIT extends BaseIntegrationTest{ VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse(); mockResponse.setMessage("Error in rollback Vf module"); stubFor( - post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID + "/rollback")) + delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID + "/rollback")) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500))); @@ -134,7 +135,7 @@ public class VnfAdapterClientIT extends BaseIntegrationTest{ DeleteVfModuleResponse mockResponse = new DeleteVfModuleResponse(); mockResponse.setVfModuleDeleted(true); - stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID)) + stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID)) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBody(mapper.writeValueAsString(mockResponse)).withStatus(200))); @@ -149,7 +150,7 @@ public class VnfAdapterClientIT extends BaseIntegrationTest{ VfModuleExceptionResponse mockResponse = new VfModuleExceptionResponse(); mockResponse.setMessage("Error in delete Vf module"); - stubFor(post(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID)) + stubFor(delete(urlPathEqualTo(REST_ENDPOINT + "/" + AAI_VNF_ID + "/vf-modules/" + AAI_VF_MODULE_ID)) .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBody(mapper.writeValueAsString(mockResponse)).withStatus(500))); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java index 0ca80c75f7..302bb551c3 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/GCTopologyOperationRequestMapperTest.java @@ -75,6 +75,7 @@ public class GCTopologyOperationRequestMapperTest extends TestDataSetup { Assert.assertEquals("VLAN-NETWORK-RECEPTOR", genericInfo.getConfigurationInformation().getConfigurationType()); Assert.assertEquals("uuid",genericInfo.getSdncRequestHeader().getSvcRequestId()); Assert.assertEquals("http://localhost",genericInfo.getSdncRequestHeader().getSvcNotificationUrl()); + Assert.assertEquals("MsoRequestId",genericInfo.getRequestInformation().getRequestId()); } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapperTest.java index 6a14f8b567..1bfa78ad6d 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/NetworkTopologyOperationRequestMapperTest.java @@ -23,6 +23,7 @@ package org.onap.so.client.sdnc.mapper; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.io.IOException; @@ -109,6 +110,7 @@ public class NetworkTopologyOperationRequestMapperTest { userParams.put("key1", "value1"); requestContext.setUserParams(userParams); requestContext.setProductFamilyId("productFamilyId"); + requestContext.setMsoRequestId("MsoRequestId"); network = new L3Network(); network.setNetworkId("TEST_NETWORK_ID"); @@ -138,8 +140,24 @@ public class NetworkTopologyOperationRequestMapperTest { assertThat(networkSDNCrequest, sameBeanAs(reqMapper1).ignoring("sdncRequestHeader.svcRequestId") .ignoring("requestInformation.requestId")); + assertEquals("MsoRequestId", networkSDNCrequest.getRequestInformation().getRequestId()); } + + @Test + public void createGenericResourceApiNetworkOperationInformationReqContextNullTest() throws Exception { + RequestContext rc = new RequestContext(); + rc.setMsoRequestId(null); + GenericResourceApiNetworkOperationInformation networkSDNCrequest = mapper.reqMapper( + SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer, + rc, cloudRegion); + assertNotNull(networkSDNCrequest.getRequestInformation().getRequestId()); + GenericResourceApiNetworkOperationInformation networkSDNCrequest2 = mapper.reqMapper( + SDNCSvcOperation.NETWORK_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATENETWORKINSTANCE, network, serviceInstance, customer, + null, cloudRegion); + assertNotNull(networkSDNCrequest2.getRequestInformation().getRequestId()); + } + @Test public void reqMapperTest() throws Exception { @@ -175,7 +193,8 @@ public class NetworkTopologyOperationRequestMapperTest { assertThat(reqMapperUnassign, sameBeanAs(networkSDNCrequestUnassign).ignoring("sdncRequestHeader.svcRequestId") .ignoring("requestInformation.requestId")); - + assertEquals("MsoRequestId", networkSDNCrequestUnassign.getRequestInformation().getRequestId()); + } @Test diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapperTest.java index 0bf06a0bb0..1919ef437b 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/ServiceTopologyOperationMapperTest.java @@ -22,6 +22,8 @@ package org.onap.so.client.sdnc.mapper; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.nio.file.Files; import java.nio.file.Paths; @@ -80,10 +82,14 @@ public class ServiceTopologyOperationMapperTest { userParams.put("key1", "value1"); requestContext.setUserParams(userParams); requestContext.setProductFamilyId("productFamilyId"); + requestContext.setMsoRequestId("MsoRequestId"); GenericResourceApiServiceOperationInformation serviceOpInformation = mapper.reqMapper( SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer, requestContext); + GenericResourceApiServiceOperationInformation serviceOpInformationNullReqContext = mapper.reqMapper( + SDNCSvcOperation.SERVICE_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN, GenericResourceApiRequestActionEnumeration.CREATESERVICEINSTANCE, serviceInstance, customer, + null); String jsonToCompare = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/BuildingBlocks/genericResourceApiEcompModelInformation.json"))); @@ -92,5 +98,7 @@ public class ServiceTopologyOperationMapperTest { GenericResourceApiOnapmodelinformationOnapModelInformation.class); assertThat(reqMapper1, sameBeanAs(serviceOpInformation.getServiceInformation().getOnapModelInformation())); + assertEquals("MsoRequestId", serviceOpInformation.getRequestInformation().getRequestId()); + assertNotNull(serviceOpInformationNullReqContext.getRequestInformation().getRequestId()); } } diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java index 282f23caa7..7fce8c48c8 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VfModuleTopologyOperationRequestMapperTest.java @@ -23,6 +23,7 @@ package org.onap.so.client.sdnc.mapper; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.nio.file.Files; @@ -102,6 +103,7 @@ public class VfModuleTopologyOperationRequestMapperTest { RequestParameters requestParameters = new RequestParameters(); requestParameters.setUsePreload(true); requestContext.setRequestParameters(requestParameters); + requestContext.setMsoRequestId("MsoRequestId"); GenericVnf vnf = new GenericVnf(); vnf.setVnfId("testVnfId"); @@ -148,6 +150,7 @@ public class VfModuleTopologyOperationRequestMapperTest { assertThat(reqMapper1, sameBeanAs(vfModuleSDNCrequest).ignoring("sdncRequestHeader.svcRequestId") .ignoring("requestInformation.requestId")); + assertEquals("MsoRequestId", vfModuleSDNCrequest.getRequestInformation().getRequestId()); } @Test @@ -168,10 +171,13 @@ public class VfModuleTopologyOperationRequestMapperTest { VfModule vfModule = new VfModule(); vfModule.setVfModuleId("testVfModuleId"); vfModule.setVfModuleName("testVfModuleName"); + + RequestContext requestContext = new RequestContext(); + requestContext.setMsoRequestId("MsoRequestId"); GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper( SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null, - null, null, null); + null, requestContext, null); String jsonToCompare = new String(Files.readAllBytes(Paths.get(JSON_FILE_LOCATION + "genericResourceApiVfModuleOperationInformationUnassign.json"))); @@ -182,6 +188,35 @@ public class VfModuleTopologyOperationRequestMapperTest { assertThat(reqMapper1, sameBeanAs(vfModuleSDNCrequest).ignoring("sdncRequestHeader.svcRequestId") .ignoring("requestInformation.requestId")); + assertEquals("MsoRequestId", vfModuleSDNCrequest.getRequestInformation().getRequestId()); + } + + @Test + public void unassignGenericResourceApiVfModuleInformationNullMsoReqIdTest() throws Exception { + + // prepare and set service instance + ServiceInstance serviceInstance = new ServiceInstance(); + serviceInstance.setServiceInstanceId("serviceInstanceId"); + + // prepare and set vnf instance + + GenericVnf vnf = new GenericVnf(); + vnf.setVnfId("testVnfId"); + vnf.setVnfType("testVnfType"); + + // prepare and set vf module instance + + VfModule vfModule = new VfModule(); + vfModule.setVfModuleId("testVfModuleId"); + vfModule.setVfModuleName("testVfModuleName"); + + RequestContext requestContext = new RequestContext(); + + GenericResourceApiVfModuleOperationInformation vfModuleSDNCrequest = mapper.reqMapper( + SDNCSvcOperation.VF_MODULE_TOPOLOGY_OPERATION, SDNCSvcAction.UNASSIGN, vfModule, null, vnf, serviceInstance, null, + null, requestContext, null); + + assertNotNull(vfModuleSDNCrequest.getRequestInformation().getRequestId()); } @Test diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapperTest.java index 229a8cf601..64b532fd07 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/sdnc/mapper/VnfTopologyOperationRequestMapperTest.java @@ -21,6 +21,7 @@ package org.onap.so.client.sdnc.mapper; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.ArrayList; @@ -122,12 +123,16 @@ public class VnfTopologyOperationRequestMapperTest { userParams.put("key1", "value1"); requestContext.setUserParams(userParams); requestContext.setProductFamilyId("productFamilyId"); + requestContext.setMsoRequestId("MsoRequestId"); CloudRegion cloudRegion = new CloudRegion(); GenericResourceApiVnfOperationInformation vnfOpInformation = mapper.reqMapper( SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer, cloudRegion, requestContext,true); + GenericResourceApiVnfOperationInformation vnfOpInformationNullReqContext = mapper.reqMapper( + SDNCSvcOperation.VNF_TOPOLOGY_OPERATION, SDNCSvcAction.ASSIGN,GenericResourceApiRequestActionEnumeration.CREATEVNFINSTANCE, vnf, serviceInstance, customer, + cloudRegion, null,true); assertNull(vnfOpInformation.getServiceInformation().getOnapModelInformation().getModelCustomizationUuid()); assertEquals("vnfModelCustomizationUUID", vnfOpInformation.getVnfInformation().getOnapModelInformation().getModelCustomizationUuid()); @@ -136,5 +141,7 @@ public class VnfTopologyOperationRequestMapperTest { assertEquals("l3-network-ig-222", vnfOpInformation.getVnfRequestInput().getVnfNetworkInstanceGroupIds().get(1).getVnfNetworkInstanceGroupId()); assertEquals("entitlementPoolUuid", vnfOpInformation.getVnfRequestInput().getVnfInputParameters().getParam().get(1).getValue()); assertEquals("licenseKeyGroupUuid", vnfOpInformation.getVnfRequestInput().getVnfInputParameters().getParam().get(2).getValue()); + assertEquals("MsoRequestId", vnfOpInformation.getRequestInformation().getRequestId()); + assertNotNull(vnfOpInformationNullReqContext.getRequestInformation().getRequestId()); } } diff --git a/common/src/main/java/org/onap/so/client/RestRequest.java b/common/src/main/java/org/onap/so/client/RestRequest.java index 6f0d71cabf..3864f2e5cc 100644 --- a/common/src/main/java/org/onap/so/client/RestRequest.java +++ b/common/src/main/java/org/onap/so/client/RestRequest.java @@ -25,6 +25,7 @@ package org.onap.so.client; import java.util.Optional; import java.util.concurrent.Callable; +import javax.ws.rs.HttpMethod; import javax.ws.rs.NotFoundException; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Response; @@ -60,8 +61,8 @@ public class RestRequest implements Callable<Response> { response = this.client.getBuilder().accept(this.client.getAccept()).delete(); } else { - response = this.client.getBuilder().header("X-HTTP-Method-Override", "DELETE").accept(this.client.getAccept()) - .post(Entity.entity(entity, this.client.getContentType())); + response = this.client.getBuilder().accept(this.client.getAccept()) + .build(HttpMethod.DELETE, Entity.entity(entity, this.client.getContentType())).invoke(); } } else if ("PUT".equals(method)) { response = this.client.getBuilder().accept(this.client.getAccept()).put(Entity.entity(entity, this.client.getContentType())); diff --git a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java index 174c76b1ef..c63d602bca 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java @@ -150,7 +150,7 @@ public class AAIResourcesClientTest { AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test2"); AAIResourceUri path2 = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3"); - wireMockRule.stubFor(post( + wireMockRule.stubFor(delete( urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build() + "/relationship-list/relationship")) .willReturn( aResponse() diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java new file mode 100644 index 0000000000..1580c9fb34 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -0,0 +1,206 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.apache.http.HttpStatus; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.exceptions.ValidationException; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestReferences; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.util.HashMap; + +@Component +@Path("/onap/so/infra/instanceManagement") +@Api(value="/onap/so/infra/instanceManagement",description="Infrastructure API Requests for Instance Management") +public class InstanceManagement { + + private static Logger logger = LoggerFactory.getLogger(InstanceManagement.class); + private static String uriPrefix = "/instanceManagement/"; + private static final String SAVE_TO_DB = "save instance to db"; + + @Autowired + private RequestsDbClient infraActiveRequestsClient; + + @Autowired + private MsoRequest msoRequest; + + @Autowired + private RequestHandlerUtils requestHandlerUtils; + + @POST + @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value="Execute custom workflow",response=Response.class) + @Transactional + public Response executeCustomWorkflow(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("workflowUuid", workflowUuid); + return processCustomWorkflowRequest(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId, requestContext); + } + + private Response processCustomWorkflowRequest(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, ContainerRequestContext requestContext) throws ApiException { + String serviceInstanceId = null; + if (instanceIdMap != null) { + serviceInstanceId = instanceIdMap.get("serviceInstanceId"); + } + Boolean aLaCarte = true; + long startTime = System.currentTimeMillis (); + ServiceInstancesRequest sir = null; + String apiVersion = version.substring(1); + + String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); + + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri); + String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); + InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); + + try { + requestHandlerUtils.validateHeaders(requestContext); + } catch (ValidationException e) { + logger.error("Exception occurred", e); + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) + .errorInfo(errorLoggerInfo).build(); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + throw validateException; + } + + requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq); + requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); + + int requestVersion = Integer.parseInt(version.substring(1)); + String vnfType = msoRequest.getVnfType(sir,requestScope,action,requestVersion); + + if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null){ + currentActiveReq.setVnfType(vnfType); + } + + InfraActiveRequests dup = null; + boolean inProgress = false; + + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, currentActiveReq); + + if(dup != null){ + inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); + } + + if (dup != null && inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, null, requestScope, dup); + } + ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); + + RequestReferences referencesResponse = new RequestReferences(); + + referencesResponse.setRequestId(requestId); + + serviceResponse.setRequestReferences(referencesResponse); + Boolean isBaseVfModule = false; + + String workflowUuid = null; + if (instanceIdMap !=null) { + workflowUuid = instanceIdMap.get("workflowUuid"); + } + + RecipeLookupResult recipeLookupResult = getCustomWorkflowUri(workflowUuid); + String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, true); + + serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir); + String vnfId = ""; + + if(sir.getVnfInstanceId () != null){ + vnfId = sir.getVnfInstanceId (); + } + + try{ + infraActiveRequestsClient.save(currentActiveReq); + }catch(Exception e){ + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) + .errorInfo(errorLoggerInfo).build(); + } + + RequestClientParameter requestClientParameter = null; + try { + requestClientParameter = new RequestClientParameter.Builder() + .setRequestId(requestId) + .setBaseVfModule(isBaseVfModule) + .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.toString()) + .setServiceInstanceId(serviceInstanceId) + .setVnfId(vnfId) + .setServiceType(serviceInstanceType) + .setVnfType(vnfType) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) + .setApiVersion(apiVersion) + .setALaCarte(aLaCarte) + .setRequestUri(requestUri) + .build(); + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) + .errorInfo(errorLoggerInfo).build(); + } + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); + } + + private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) { + + RecipeLookupResult recipeLookupResult = new RecipeLookupResult("/mso/async/services/VnfInPlaceUpdate", 180); + return recipeLookupResult; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java index 5790f1afe9..434b9e9364 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java @@ -63,6 +63,7 @@ public class JerseyConfiguration extends ResourceConfig { register(RequestUriFilter.class); register(E2EServiceInstances.class); register(WorkflowSpecificationsHandler.class); + register(InstanceManagement.class); // this registration seems to be needed to get predictable // execution behavior for the above JSON Exception Mappers register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java index de7d26379c..dc8e6b6958 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java @@ -50,6 +50,7 @@ import org.onap.so.apihandlerinfra.validation.MembersValidation; import org.onap.so.apihandlerinfra.validation.ApplyUpdatedConfigValidation; import org.onap.so.apihandlerinfra.validation.CloudConfigurationValidation; import org.onap.so.apihandlerinfra.validation.ConfigurationParametersValidation; +import org.onap.so.apihandlerinfra.validation.CustomWorkflowValidation; import org.onap.so.apihandlerinfra.validation.InPlaceSoftwareUpdateValidation; import org.onap.so.apihandlerinfra.validation.InstanceIdMapValidation; import org.onap.so.apihandlerinfra.validation.ModelInfoValidation; @@ -175,7 +176,14 @@ public class MsoRequest { rules.add(new InstanceIdMapValidation()); - if(reqVersion >= 6 && action == Action.inPlaceSoftwareUpdate){ + String workflowUuid = null; + if (instanceIdMap != null) { + workflowUuid = instanceIdMap.get("workflowUuid"); + } + + if (workflowUuid != null) { + rules.add(new CustomWorkflowValidation()); + }else if(reqVersion >= 6 && action == Action.inPlaceSoftwareUpdate){ rules.add(new InPlaceSoftwareUpdateValidation()); }else if(reqVersion >= 6 && action == Action.applyUpdatedConfig){ rules.add(new ApplyUpdatedConfigValidation()); @@ -361,7 +369,9 @@ public class MsoRequest { aq.setInstanceGroupName(requestInfo.getInstanceName()); } if(ModelType.vnf.name().equalsIgnoreCase(requestScope)){ - aq.setVnfName(requestInfo.getInstanceName()); + if (requestInfo != null) { + aq.setVnfName(requestInfo.getInstanceName()); + } if (null != servInsReq.getRequestDetails()) { RelatedInstanceList[] instanceList = servInsReq.getRequestDetails().getRelatedInstanceList(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java new file mode 100644 index 0000000000..c02b40aeca --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -0,0 +1,567 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra; + + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.camundabeans.CamundaResponse; +import org.onap.so.apihandler.common.CommonConstants; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.RequestClient; +import org.onap.so.apihandler.common.RequestClientFactory; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandler.common.ResponseBuilder; +import org.onap.so.apihandler.common.ResponseHandler; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; +import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.exceptions.ValidationException; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LogConstants; +import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RelatedInstance; +import org.onap.so.serviceinstancebeans.RelatedInstanceList; +import org.onap.so.serviceinstancebeans.RequestParameters; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.onap.so.utils.CryptoUtils; +import org.onap.so.utils.UUIDChecker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.xml.bind.DatatypeConverter; + +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; + +import java.io.IOException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Component +public class RequestHandlerUtils { + + private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class); + + private static final String SAVE_TO_DB = "save instance to db"; + + @Autowired + private Environment env; + + @Autowired + private RequestClientFactory reqClientFactory; + + @Autowired + private RequestsDbClient infraActiveRequestsClient; + + @Autowired + private ResponseBuilder builder; + + @Autowired + private MsoRequest msoRequest; + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private CatalogDbClient catalogDbClient; + + public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter, String orchestrationUri, String requestScope)throws ApiException { + RequestClient requestClient = null; + HttpResponse response = null; + try { + requestClient = reqClientFactory.getRequestClient (orchestrationUri); + response = requestClient.post(requestClientParameter); + } catch (Exception e) { + + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + String url = requestClient != null ? requestClient.getUrl() : ""; + ClientConnectionException clientException = new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); + + throw clientException; + } + + if (response == null) { + + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); + + updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); + + throw clientException; + } + + ResponseHandler respHandler = null; + int bpelStatus = 500; + try { + respHandler = new ResponseHandler (response, requestClient.getType ()); + bpelStatus = respHandler.getStatus (); + } catch (ApiException e) { + logger.error("Exception occurred", e); + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + throw validateException; + } + + // BPEL accepted the request, the request is in progress + if (bpelStatus == HttpStatus.SC_ACCEPTED) { + ServiceInstancesResponse jsonResponse; + CamundaResponse camundaResp = respHandler.getResponse(); + + if("Success".equalsIgnoreCase(camundaResp.getMessage())) { + try { + ObjectMapper mapper = new ObjectMapper(); + jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class); + jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId()); + Optional<URL> selfLinkUrl = msoRequest.buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId()); + if(selfLinkUrl.isPresent()){ + jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get()); + } else { + jsonResponse.getRequestReferences().setRequestSelfLink(null); + } + } catch (IOException e) { + logger.error("Exception occurred", e); + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + throw validateException; + } + return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(), jsonResponse, requestClientParameter.getApiVersion()); + } + } + + List<String> variables = new ArrayList<>(); + variables.add(bpelStatus + ""); + String camundaJSONResponseBody = respHandler.getResponseBody (); + if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty ()) { + + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).errorSource(requestClient.getUrl()).build(); + BPMNFailureException bpmnException = new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) + .errorInfo(errorLoggerInfo).build(); + + updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage()); + + throw bpmnException; + } else { + + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).errorSource(requestClient.getUrl()).build(); + + + BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, servException.getMessage()); + + throw servException; + } + } + + public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage) throws RequestDbFailureException{ + if ((status == Status.FAILED) || (status == Status.COMPLETE)) { + aq.setStatusMessage (errorMessage); + aq.setProgress(new Long(100)); + aq.setRequestStatus(status.toString()); + Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis()); + aq.setEndTime (endTimeStamp); + try{ + infraActiveRequestsClient.save(aq); + }catch(Exception e){ + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) + .errorInfo(errorLoggerInfo).build(); + } + } + } + + public String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) { + if(action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig){ + return (ModelType.vnf.name()); + }else if(action == Action.addMembers || action == Action.removeMembers){ + return(ModelType.instanceGroup.toString()); + }else{ + String requestScope; + if(sir.getRequestDetails().getModelInfo().getModelType() == null){ + requestScope = requestScopeFromUri(requestUri); + }else{ + requestScope = sir.getRequestDetails().getModelInfo().getModelType().name(); + } + return requestScope; + } + } + + + public void validateHeaders(ContainerRequestContext context) throws ValidationException{ + MultivaluedMap<String, String> headers = context.getHeaders(); + if(!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)){ + throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true); + } + if(!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)){ + throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true); + } + if(!headers.containsKey(REQUESTOR_ID)){ + throw new ValidationException(REQUESTOR_ID + " header", true); + } + } + + public String getRequestUri(ContainerRequestContext context, String uriPrefix){ + String requestUri = context.getUriInfo().getPath(); + String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri); + MDC.put(LogConstants.HTTP_URL, httpUrl); + requestUri = requestUri.substring(requestUri.indexOf(uriPrefix) + uriPrefix.length()); + return requestUri; + } + + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, + MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { + InfraActiveRequests dup = null; + try { + if(!(instanceName==null && requestScope.equals("service") && (action == Action.createInstance || action == Action.activateInstance || action == Action.assignInstance))){ + dup = infraActiveRequestsClient.checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope); + } + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + RequestDbFailureException requestDbFailureException = new RequestDbFailureException.Builder("check for duplicate instance", e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage()); + throw requestDbFailureException; + } + return dup; + } + + public boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq) throws RequestDbFailureException, ContactCamundaException{ + String requestId = duplicateRecord.getRequestId(); + String path = env.getProperty("mso.camunda.rest.history.uri") + requestId; + String targetUrl = env.getProperty("mso.camundaURL") + path; + HttpHeaders headers = setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = null; + try{ + response = restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>(){}); + }catch(HttpStatusCodeException e){ + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ContactCamundaException contactCamundaException= new ContactCamundaException.Builder(requestId, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage()); + throw contactCamundaException; + } + if(response.getBody().isEmpty()){ + updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); + } + for(HistoricProcessInstance instance : response.getBody()){ + if(instance.getState().equals("ACTIVE")){ + return true; + }else{ + updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); + } + } + return false; + } + + protected HttpHeaders setCamundaHeaders(String auth, String msoKey) { + HttpHeaders headers = new HttpHeaders(); + List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); + acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); + headers.setAccept(acceptableMediaTypes); + try { + String userCredentials = CryptoUtils.decrypt(auth, msoKey); + if(userCredentials != null) { + headers.add(HttpHeaders.AUTHORIZATION, "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes())); + } + } catch(GeneralSecurityException e) { + logger.error("Security exception", e); + } + return headers; + } + + public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, long startTime, + ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) throws ApiException { + try{ + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(requestJSON, ServiceInstancesRequest.class); + + } catch (IOException e) { + + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + + ValidateException validateException = new ValidateException.Builder("Error mapping request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) + .errorInfo(errorLoggerInfo).build(); + String requestScope = requestScopeFromUri(requestUri); + + msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action, requestScope, requestJSON); + + throw validateException; + } + } + + public void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action, String version, + String requestJSON, Boolean aLaCarte, String requestId, InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException { + int reqVersion = Integer.parseInt(version.substring(1)); + try { + msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte); + } catch (Exception e) { + logger.error("failed to parse request", e); + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) + .errorInfo(errorLoggerInfo).build(); + + updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + + throw validateException; + } + } + + public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, + String instanceName, String requestScope, InfraActiveRequests dup) throws ApiException { + + String instance = null; + if(instanceName != null){ + instance = instanceName; + }else{ + instance = instanceIdMap.get(requestScope + "InstanceId"); + } + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + + DuplicateRequestException dupException = new DuplicateRequestException.Builder(requestScope,instance,dup.getRequestStatus(),dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) + .errorInfo(errorLoggerInfo).build(); + + updateStatus(currentActiveReq, Status.FAILED, dupException.getMessage()); + + throw dupException; + } + + public String getRequestId(ContainerRequestContext requestContext) throws ValidateException { + String requestId = null; + if (requestContext.getProperty("requestId") != null) { + requestId = requestContext.getProperty("requestId").toString(); + } + if (UUIDChecker.isValidUUID(requestId)) { + return requestId; + } else { + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) + .errorInfo(errorLoggerInfo).build(); + + throw validateException; + } + } + + public void setInstanceId(InfraActiveRequests currentActiveReq, String requestScope, String instanceId, Map<String, String> instanceIdMap) { + if(StringUtils.isNotBlank(instanceId)) { + if(ModelType.service.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setServiceInstanceId(instanceId); + } else if(ModelType.vnf.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setVnfId(instanceId); + } else if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setVfModuleId(instanceId); + } else if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setVolumeGroupId(instanceId); + } else if(ModelType.network.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setNetworkId(instanceId); + } else if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setConfigurationId(instanceId); + }else if(ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)){ + currentActiveReq.setInstanceGroupId(instanceId); + } + } else if(instanceIdMap != null && !instanceIdMap.isEmpty()) { + if(instanceIdMap.get("serviceInstanceId") != null){ + currentActiveReq.setServiceInstanceId(instanceIdMap.get("serviceInstanceId")); + } + if(instanceIdMap.get("vnfInstanceId") != null){ + currentActiveReq.setVnfId(instanceIdMap.get("vnfInstanceId")); + } + if(instanceIdMap.get("vfModuleInstanceId") != null){ + currentActiveReq.setVfModuleId(instanceIdMap.get("vfModuleInstanceId")); + } + if(instanceIdMap.get("volumeGroupInstanceId") != null){ + currentActiveReq.setVolumeGroupId(instanceIdMap.get("volumeGroupInstanceId")); + } + if(instanceIdMap.get("networkInstanceId") != null){ + currentActiveReq.setNetworkId(instanceIdMap.get("networkInstanceId")); + } + if(instanceIdMap.get("configurationInstanceId") != null){ + currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId")); + } + if(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null){ + currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); + } + } + } + + public String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest, boolean isAlaCarte, Actions action) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + if(msoRawRequest != null){ + ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class); + if( serviceInstRequest != null && + serviceInstRequest.getRequestDetails() != null && + serviceInstRequest.getRequestDetails().getRequestParameters() != null) { + if( !isAlaCarte && Action.createInstance.equals(action)) { + sir.getRequestDetails().setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration()); + sir.getRequestDetails().getRequestParameters().setUserParams(serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams()); + } + sir.getRequestDetails().getRequestParameters().setUsePreload(serviceInstRequest.getRequestDetails().getRequestParameters().getUsePreload()); + } + + logger.debug("Value as string: {}", mapper.writeValueAsString(sir)); + return mapper.writeValueAsString(sir); + } + return null; + } + + public Optional<String> retrieveModelName(RequestParameters requestParams) { + String requestTestApi = null; + TestApi testApi = null; + + if (requestParams != null) { + requestTestApi = requestParams.getTestApi(); + } + + if (requestTestApi == null) { + if(requestParams != null && requestParams.getALaCarte() != null && !requestParams.getALaCarte()) { + requestTestApi = env.getProperty(CommonConstants.MACRO_TEST_API); + } else { + requestTestApi = env.getProperty(CommonConstants.ALACARTE_TEST_API); + } + } + + try { + testApi = TestApi.valueOf(requestTestApi); + return Optional.of(testApi.getModelName()); + } catch (Exception e) { + logger.warn("Catching the exception on the valueOf enum call and continuing", e); + throw new IllegalArgumentException("Invalid TestApi is provided", e); + } + } + + public String getDefaultModel(ServiceInstancesRequest sir) { + String defaultModel = sir.getRequestDetails().getRequestInfo().getSource() + "_DEFAULT"; + Optional<String> oModelName = retrieveModelName(sir.getRequestDetails().getRequestParameters()); + if (oModelName.isPresent()) { + defaultModel = oModelName.get(); + } + return defaultModel; + } + + public String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag){ + String serviceType = null; + if(requestScope.equalsIgnoreCase(ModelType.service.toString())){ + String defaultServiceModelName = getDefaultModel(sir); + org.onap.so.db.catalog.beans.Service serviceRecord; + if(aLaCarteFlag){ + serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); + if(serviceRecord != null){ + serviceType = serviceRecord.getServiceType(); + } + }else{ + serviceRecord = catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId()); + if(serviceRecord != null){ + serviceType = serviceRecord.getServiceType(); + }else{ + serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); + if(serviceRecord != null){ + serviceType = serviceRecord.getServiceType(); + } + } + } + }else{ + serviceType = msoRequest.getServiceInstanceType(sir, requestScope); + } + return serviceType; + } + + protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir){ + if(sir.getServiceInstanceId () != null){ + return sir.getServiceInstanceId (); + }else if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())){ + RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList(); + if(relatedInstances != null){ + for(RelatedInstanceList relatedInstanceList : relatedInstances){ + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + if(relatedInstance.getModelInfo().getModelType() == ModelType.service){ + return relatedInstance.getInstanceId(); + } + } + } + } + return null; + } + + private String requestScopeFromUri(String requestUri){ + String requestScope; + if(requestUri.contains(ModelType.network.name())){ + requestScope = ModelType.network.name(); + }else if(requestUri.contains(ModelType.vfModule.name())){ + requestScope = ModelType.vfModule.name(); + }else if(requestUri.contains(ModelType.volumeGroup.name())){ + requestScope = ModelType.volumeGroup.name(); + }else if(requestUri.contains(ModelType.configuration.name())){ + requestScope = ModelType.configuration.name(); + }else if(requestUri.contains(ModelType.vnf.name())){ + requestScope = ModelType.vnf.name(); + }else{ + requestScope = ModelType.service.name(); + } + return requestScope; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java index 8c5904fb21..c6a45d540c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java @@ -23,8 +23,6 @@ package org.onap.so.apihandlerinfra; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -32,22 +30,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; -import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.apihandler.camundabeans.CamundaResponse; import org.onap.so.apihandler.common.CommonConstants; import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandler.common.RequestClient; -import org.onap.so.apihandler.common.RequestClientFactory; import org.onap.so.apihandler.common.RequestClientParameter; -import org.onap.so.apihandler.common.ResponseBuilder; -import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; -import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; -import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; -import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException; import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; @@ -67,7 +54,6 @@ import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.LogConstants; import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.ModelInfo; @@ -83,23 +69,11 @@ import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; import org.onap.so.serviceinstancebeans.VfModules; import org.onap.so.serviceinstancebeans.Vnfs; -import org.onap.so.utils.CryptoUtils; -import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.env.Environment; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import org.springframework.web.client.HttpStatusCodeException; -import org.springframework.web.client.RestTemplate; -import org.camunda.bpm.engine.history.HistoricProcessInstance; -import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; import javax.transaction.Transactional; import javax.ws.rs.Consumes; @@ -112,21 +86,14 @@ import javax.ws.rs.Produces; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; import java.io.IOException; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; -import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; - @Component @Path("/onap/so/infra/serviceInstantiation") @Api(value="/onap/so/infra/serviceInstantiation",description="Infrastructure API Requests for Service Instances") @@ -135,28 +102,23 @@ public class ServiceInstances { private static Logger logger = LoggerFactory.getLogger(MsoRequest.class); private static String NAME = "name"; private static String VALUE = "value"; + private static String uriPrefix = "/serviceInstantiation/"; private static final String SAVE_TO_DB = "save instance to db"; @Autowired private Environment env; @Autowired - private RequestClientFactory reqClientFactory; - - @Autowired private CatalogDbClient catalogDbClient; @Autowired private RequestsDbClient infraActiveRequestsClient; @Autowired - private ResponseBuilder builder; - - @Autowired private MsoRequest msoRequest; @Autowired - private RestTemplate restTemplate; + private RequestHandlerUtils requestHandlerUtils; @POST @Path("/{version:[vV][5-7]}/serviceInstances") @@ -165,8 +127,8 @@ public class ServiceInstances { @ApiOperation(value="Create a Service Instance on a version provided",response=Response.class) @Transactional public Response createServiceInstance(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - return serviceInstances(request, Action.createInstance, null, version, requestId, getRequestUri(requestContext)); + String requestId = requestHandlerUtils.getRequestId(requestContext); + return serviceInstances(request, Action.createInstance, null, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -176,10 +138,10 @@ public class ServiceInstances { @ApiOperation(value="Activate provided Service Instance",response=Response.class) @Transactional public Response activateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.activateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.activateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -189,10 +151,10 @@ public class ServiceInstances { @ApiOperation(value="Deactivate provided Service Instance",response=Response.class) @Transactional public Response deactivateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.deactivateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.deactivateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @DELETE @@ -202,10 +164,10 @@ public class ServiceInstances { @ApiOperation(value="Delete provided Service Instance",response=Response.class) @Transactional public Response deleteServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -215,8 +177,8 @@ public class ServiceInstances { @ApiOperation(value="Assign Service Instance", response=Response.class) @Transactional public Response assignServiceInstance(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - return serviceInstances(request, Action.assignInstance, null, version, requestId, getRequestUri(requestContext)); + String requestId = requestHandlerUtils.getRequestId(requestContext); + return serviceInstances(request, Action.assignInstance, null, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -226,10 +188,10 @@ public class ServiceInstances { @ApiOperation(value="Unassign Service Instance", response=Response.class) @Transactional public Response unassignServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<String,String>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.unassignInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.unassignInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -239,10 +201,10 @@ public class ServiceInstances { @ApiOperation(value="Create Port Mirroring Configuration",response=Response.class) @Transactional public Response createPortConfiguration(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return configurationRecipeLookup(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return configurationRecipeLookup(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @DELETE @@ -253,11 +215,11 @@ public class ServiceInstances { @Transactional public Response deletePortConfiguration(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return configurationRecipeLookup(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -268,11 +230,11 @@ public class ServiceInstances { @Transactional public Response enablePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.enablePort, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return configurationRecipeLookup(request, Action.enablePort, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -283,11 +245,11 @@ public class ServiceInstances { @Transactional public Response disablePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.disablePort, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return configurationRecipeLookup(request, Action.disablePort, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -298,11 +260,11 @@ public class ServiceInstances { @Transactional public Response activatePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.activateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return configurationRecipeLookup(request, Action.activateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -313,11 +275,11 @@ public class ServiceInstances { @Transactional public Response deactivatePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.deactivateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return configurationRecipeLookup(request, Action.deactivateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -327,10 +289,10 @@ public class ServiceInstances { @ApiOperation(value="Add Relationships to a Service Instance",response=Response.class) @Transactional public Response addRelationships(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return configurationRecipeLookup(request, Action.addRelationships, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return configurationRecipeLookup(request, Action.addRelationships, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -340,10 +302,10 @@ public class ServiceInstances { @ApiOperation(value="Remove Relationships from Service Instance",response=Response.class) @Transactional public Response removeRelationships(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return configurationRecipeLookup(request, Action.removeRelationships, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return configurationRecipeLookup(request, Action.removeRelationships, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -353,10 +315,10 @@ public class ServiceInstances { @ApiOperation(value="Create VNF on a specified version and serviceInstance",response=Response.class) @Transactional public Response createVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -367,11 +329,11 @@ public class ServiceInstances { @Transactional public Response replaceVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @PUT @@ -382,11 +344,11 @@ public class ServiceInstances { @Transactional public Response updateVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -396,11 +358,11 @@ public class ServiceInstances { @ApiOperation(value="Apply updated configuration",response=Response.class) public Response applyUpdatedConfig(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.applyUpdatedConfig, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.applyUpdatedConfig, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -410,11 +372,11 @@ public class ServiceInstances { @ApiOperation(value="Recreate VNF Instance",response=Response.class) public Response recreateVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.recreateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.recreateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @@ -426,11 +388,11 @@ public class ServiceInstances { @Transactional public Response deleteVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -441,11 +403,11 @@ public class ServiceInstances { @Transactional public Response createVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -457,12 +419,12 @@ public class ServiceInstances { public Response replaceVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); - return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @PUT @@ -474,12 +436,12 @@ public class ServiceInstances { public Response updateVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); - return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -490,11 +452,11 @@ public class ServiceInstances { @Transactional public Response inPlaceSoftwareUpdate(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @DELETE @@ -506,12 +468,12 @@ public class ServiceInstances { public Response deleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -522,12 +484,12 @@ public class ServiceInstances { @Transactional public Response deactivateAndCloudDeleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); - Response response = serviceInstances(request, Action.deactivateAndCloudDelete, instanceIdMap, version, requestId, getRequestUri(requestContext)); + Response response = serviceInstances(request, Action.deactivateAndCloudDelete, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); return response; } @@ -539,11 +501,11 @@ public class ServiceInstances { @Transactional public Response scaleOutVfModule(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.scaleOut, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.scaleOut, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @@ -555,11 +517,11 @@ public class ServiceInstances { @Transactional public Response createVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @PUT @@ -571,12 +533,12 @@ public class ServiceInstances { public Response updateVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId); - return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @DELETE @@ -588,12 +550,12 @@ public class ServiceInstances { public Response deleteVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("vnfInstanceId", vnfInstanceId); instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -603,10 +565,10 @@ public class ServiceInstances { @ApiOperation(value="Create NetworkInstance on a specified version and serviceInstance ",response=Response.class) @Transactional public Response createNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @PUT @@ -617,11 +579,11 @@ public class ServiceInstances { @Transactional public Response updateNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("networkInstanceId", networkInstanceId); - return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @DELETE @@ -632,11 +594,11 @@ public class ServiceInstances { @Transactional public Response deleteNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); instanceIdMap.put("networkInstanceId", networkInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -646,8 +608,8 @@ public class ServiceInstances { @ApiOperation(value="Create instanceGroups",response=Response.class) @Transactional public Response createInstanceGroups(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - return serviceInstances(request, Action.createInstance, null, version, requestId, getRequestUri(requestContext)); + String requestId = requestHandlerUtils.getRequestId(requestContext); + return serviceInstances(request, Action.createInstance, null, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @DELETE @@ -657,10 +619,10 @@ public class ServiceInstances { @ApiOperation(value="Delete instanceGroup",response=Response.class) @Transactional public Response deleteInstanceGroups(@PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId); - return deleteInstanceGroups(Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext), requestContext); + return deleteInstanceGroups(Action.deleteInstance, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix), requestContext); } @POST @@ -670,10 +632,10 @@ public class ServiceInstances { @ApiOperation(value="Add instanceGroup members",response=Response.class) @Transactional public Response addInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId); - return serviceInstances(request, Action.addMembers, instanceIdMap, version, requestId, getRequestUri(requestContext)); + return serviceInstances(request, Action.addMembers, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } @POST @@ -683,33 +645,12 @@ public class ServiceInstances { @ApiOperation(value="Remove instanceGroup members",response=Response.class) @Transactional public Response removeInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); + String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId); - return serviceInstances(request, Action.removeMembers, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - public String getRequestUri(ContainerRequestContext context){ - String requestUri = context.getUriInfo().getPath(); - String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri); - MDC.put(LogConstants.HTTP_URL, httpUrl); - requestUri = requestUri.substring(requestUri.indexOf("/serviceInstantiation/") + 22); - return requestUri; + return serviceInstances(request, Action.removeMembers, instanceIdMap, version, requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); } - public void validateHeaders(ContainerRequestContext context) throws ValidationException{ - MultivaluedMap<String, String> headers = context.getHeaders(); - if(!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)){ - throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true); - } - if(!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)){ - throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true); - } - if(!headers.containsKey(REQUESTOR_ID)){ - throw new ValidationException(REQUESTOR_ID + " header", true); - } - } - public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { String serviceInstanceId = (instanceIdMap ==null)? null:instanceIdMap.get("serviceInstanceId"); Boolean aLaCarte = null; @@ -717,17 +658,20 @@ public class ServiceInstances { ServiceInstancesRequest sir = null; String apiVersion = version.substring(1); - sir = convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri); - String requestScope = deriveRequestScope(action, sir, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri); + String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); if(sir.getRequestDetails().getRequestParameters() != null){ aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); } - parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq); - setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); + requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq); + requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); int requestVersion = Integer.parseInt(version.substring(1)); - String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName(); + String instanceName = null; + if (sir.getRequestDetails().getRequestInfo() != null) { + instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName(); + } boolean alaCarteFlag = msoRequest.getAlacarteFlag(sir); String vnfType = msoRequest.getVnfType(sir,requestScope,action,requestVersion); String networkType = msoRequest.getNetworkType(sir,requestScope); @@ -743,14 +687,14 @@ public class ServiceInstances { InfraActiveRequests dup = null; boolean inProgress = false; - dup = duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq); if(dup != null){ - inProgress = camundaHistoryCheck(dup, currentActiveReq); + inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (dup != null && inProgress) { - buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -760,9 +704,9 @@ public class ServiceInstances { serviceResponse.setRequestReferences(referencesResponse); Boolean isBaseVfModule = false; - + RecipeLookupResult recipeLookupResult = getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq); - String serviceInstanceType = getServiceType(requestScope, sir, alaCarteFlag); + String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, alaCarteFlag); ModelType modelType; ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { @@ -803,14 +747,14 @@ public class ServiceInstances { String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() + serviceVersionText + " not found in MSO Catalog DB"; ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); throw vfModuleException; } } - serviceInstanceId = setServiceInstanceId(requestScope, sir); + serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir); String vnfId = ""; String vfModuleId = ""; String volumeGroupId = ""; @@ -870,7 +814,7 @@ public class ServiceInstances { .setVnfType(vnfType) .setVfModuleType(vfModuleType) .setNetworkType(networkType) - .setRequestDetails(mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) .setApiVersion(apiVersion) .setALaCarte(aLaCarte) .setRequestUri(requestUri) @@ -880,7 +824,7 @@ public class ServiceInstances { throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) .errorInfo(errorLoggerInfo).build(); } - return postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); } public Response deleteInstanceGroups(Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri, ContainerRequestContext requestContext) throws ApiException { String instanceGroupId = instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID); @@ -892,27 +836,27 @@ public class ServiceInstances { String requestScope = ModelType.instanceGroup.toString(); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, null, requestScope); - setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); + requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); try { - validateHeaders(requestContext); + requestHandlerUtils.validateHeaders(requestContext); } catch (ValidationException e) { logger.error("Exception occurred", e); ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; } - InfraActiveRequests dup = duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, currentActiveReq); + InfraActiveRequests dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, currentActiveReq); boolean inProgress = false; if(dup != null){ - inProgress = camundaHistoryCheck(dup, currentActiveReq); + inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (dup != null && inProgress) { - buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, null, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, null, requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -944,7 +888,7 @@ public class ServiceInstances { .setRequestUri(requestUri) .setInstanceGroupId(instanceGroupId).build(); - return postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); } private String getPnfCorrelationId(ServiceInstancesRequest sir) { @@ -953,315 +897,7 @@ public class ServiceInstances { .map(RequestDetails::getRequestParameters) .map(parameters -> parameters.getUserParamValue("pnfId")) .orElse(""); - } - - private String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) { - if(action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig){ - return (ModelType.vnf.name()); - }else if(action == Action.addMembers || action == Action.removeMembers){ - return(ModelType.instanceGroup.toString()); - }else{ - String requestScope; - if(sir.getRequestDetails().getModelInfo().getModelType() == null){ - requestScope = requestScopeFromUri(requestUri); - }else{ - requestScope = sir.getRequestDetails().getModelInfo().getModelType().name(); - } - return requestScope; - } - } - private String requestScopeFromUri(String requestUri){ - String requestScope; - if(requestUri.contains(ModelType.network.name())){ - requestScope = ModelType.network.name(); - }else if(requestUri.contains(ModelType.vfModule.name())){ - requestScope = ModelType.vfModule.name(); - }else if(requestUri.contains(ModelType.volumeGroup.name())){ - requestScope = ModelType.volumeGroup.name(); - }else if(requestUri.contains(ModelType.configuration.name())){ - requestScope = ModelType.configuration.name(); - }else if(requestUri.contains(ModelType.vnf.name())){ - requestScope = ModelType.vnf.name(); - }else{ - requestScope = ModelType.service.name(); - } - return requestScope; - } - private Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter, String orchestrationUri, String requestScope)throws ApiException { - RequestClient requestClient = null; - HttpResponse response = null; - try { - requestClient = reqClientFactory.getRequestClient (orchestrationUri); - response = requestClient.post(requestClientParameter); - } catch (Exception e) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - String url = requestClient != null ? requestClient.getUrl() : ""; - ClientConnectionException clientException = new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); - - throw clientException; - } - - if (response == null) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); - - throw clientException; - } - - ResponseHandler respHandler = null; - int bpelStatus = 500; - try { - respHandler = new ResponseHandler (response, requestClient.getType ()); - bpelStatus = respHandler.getStatus (); - } catch (ApiException e) { - logger.error("Exception occurred", e); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); - throw validateException; - } - - // BPEL accepted the request, the request is in progress - if (bpelStatus == HttpStatus.SC_ACCEPTED) { - ServiceInstancesResponse jsonResponse; - CamundaResponse camundaResp = respHandler.getResponse(); - - if("Success".equalsIgnoreCase(camundaResp.getMessage())) { - try { - ObjectMapper mapper = new ObjectMapper(); - jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class); - jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId()); - Optional<URL> selfLinkUrl = msoRequest.buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId()); - if(selfLinkUrl.isPresent()){ - jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get()); - } else { - jsonResponse.getRequestReferences().setRequestSelfLink(null); - } - } catch (IOException e) { - logger.error("Exception occurred", e); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); - throw validateException; - } - return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(), jsonResponse, requestClientParameter.getApiVersion()); - } - } - - List<String> variables = new ArrayList<>(); - variables.add(bpelStatus + ""); - String camundaJSONResponseBody = respHandler.getResponseBody (); - if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty ()) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).errorSource(requestClient.getUrl()).build(); - BPMNFailureException bpmnException = new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage()); - - throw bpmnException; - } else { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).errorSource(requestClient.getUrl()).build(); - - - BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, servException.getMessage()); - - throw servException; - } - } - - private void setInstanceId(InfraActiveRequests currentActiveReq, String requestScope, String instanceId, Map<String, String> instanceIdMap) { - if(StringUtils.isNotBlank(instanceId)) { - if(ModelType.service.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setServiceInstanceId(instanceId); - } else if(ModelType.vnf.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setVnfId(instanceId); - } else if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setVfModuleId(instanceId); - } else if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setVolumeGroupId(instanceId); - } else if(ModelType.network.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setNetworkId(instanceId); - } else if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setConfigurationId(instanceId); - }else if(ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)){ - currentActiveReq.setInstanceGroupId(instanceId); - } - } else if(instanceIdMap != null && !instanceIdMap.isEmpty()) { - if(instanceIdMap.get("serviceInstanceId") != null){ - currentActiveReq.setServiceInstanceId(instanceIdMap.get("serviceInstanceId")); - } - if(instanceIdMap.get("vnfInstanceId") != null){ - currentActiveReq.setVnfId(instanceIdMap.get("vnfInstanceId")); - } - if(instanceIdMap.get("vfModuleInstanceId") != null){ - currentActiveReq.setVfModuleId(instanceIdMap.get("vfModuleInstanceId")); - } - if(instanceIdMap.get("volumeGroupInstanceId") != null){ - currentActiveReq.setVolumeGroupId(instanceIdMap.get("volumeGroupInstanceId")); - } - if(instanceIdMap.get("networkInstanceId") != null){ - currentActiveReq.setNetworkId(instanceIdMap.get("networkInstanceId")); - } - if(instanceIdMap.get("configurationInstanceId") != null){ - currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId")); - } - if(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null){ - currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); - } - } - } - - protected String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest, boolean isAlaCarte, Actions action) throws IOException { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - if(msoRawRequest != null){ - ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class); - if( serviceInstRequest != null && - serviceInstRequest.getRequestDetails() != null && - serviceInstRequest.getRequestDetails().getRequestParameters() != null) { - if( !isAlaCarte && Action.createInstance.equals(action)) { - sir.getRequestDetails().setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration()); - sir.getRequestDetails().getRequestParameters().setUserParams(serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams()); - } - sir.getRequestDetails().getRequestParameters().setUsePreload(serviceInstRequest.getRequestDetails().getRequestParameters().getUsePreload()); - } - - logger.debug("Value as string: {}", mapper.writeValueAsString(sir)); - return mapper.writeValueAsString(sir); - } - return null; - } - - private void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, - String instanceName, String requestScope, InfraActiveRequests dup) throws ApiException { - - // Found the duplicate record. Return the appropriate error. - String instance = null; - if(instanceName != null){ - instance = instanceName; - }else{ - instance = instanceIdMap.get(requestScope + "InstanceId"); - } - //List<String> variables = new ArrayList<String>(); - //variables.add(dup.getRequestStatus()); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - - DuplicateRequestException dupException = new DuplicateRequestException.Builder(requestScope,instance,dup.getRequestStatus(),dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, dupException.getMessage()); - - throw dupException; - } - - private InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, - MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { - InfraActiveRequests dup = null; - try { - if(!(instanceName==null && requestScope.equals("service") && (action == Action.createInstance || action == Action.activateInstance || action == Action.assignInstance))){ - dup = infraActiveRequestsClient.checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope); - } - } catch (Exception e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - RequestDbFailureException requestDbFailureException = new RequestDbFailureException.Builder("check for duplicate instance", e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage()); - throw requestDbFailureException; - } - return dup; - } - protected boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq) throws RequestDbFailureException, ContactCamundaException{ - String requestId = duplicateRecord.getRequestId(); - String path = env.getProperty("mso.camunda.rest.history.uri") + requestId; - String targetUrl = env.getProperty("mso.camundaURL") + path; - HttpHeaders headers = setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - ResponseEntity<List<HistoricProcessInstanceEntity>> response = null; - try{ - response = restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>(){}); - }catch(HttpStatusCodeException e){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ContactCamundaException contactCamundaException= new ContactCamundaException.Builder(requestId, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage()); - throw contactCamundaException; - } - if(response.getBody().isEmpty()){ - updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); - } - for(HistoricProcessInstance instance : response.getBody()){ - if(instance.getState().equals("ACTIVE")){ - return true; - }else{ - updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); - } - } - return false; - } - protected HttpHeaders setCamundaHeaders(String auth, String msoKey) { - HttpHeaders headers = new HttpHeaders(); - List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); - acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); - headers.setAccept(acceptableMediaTypes); - try { - String userCredentials = CryptoUtils.decrypt(auth, msoKey); - if(userCredentials != null) { - headers.add(HttpHeaders.AUTHORIZATION, "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes())); - } - } catch(GeneralSecurityException e) { - logger.error("Security exception", e); - } - return headers; - } - - private ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, long startTime, - ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) throws ApiException { - try{ - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(requestJSON, ServiceInstancesRequest.class); - - } catch (IOException e) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - ValidateException validateException = new ValidateException.Builder("Error mapping request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - String requestScope = requestScopeFromUri(requestUri); - - msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action, requestScope, requestJSON); - - throw validateException; - } - } - - private void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action, String version, - String requestJSON, Boolean aLaCarte, String requestId, InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException { - int reqVersion = Integer.parseInt(version.substring(1)); - try { - msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte); - } catch (Exception e) { - logger.error("failed to parse request", e); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); - - throw validateException; - } - } + } private RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException { @@ -1284,7 +920,7 @@ public class ServiceInstances { ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; } @@ -1299,7 +935,7 @@ public class ServiceInstances { ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; } @@ -1313,7 +949,7 @@ public class ServiceInstances { ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; } @@ -1328,7 +964,7 @@ public class ServiceInstances { RecipeNotFoundException recipeNotFoundExceptionException = new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR) .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage()); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage()); throw recipeNotFoundExceptionException; } return recipeLookupResult; @@ -1338,7 +974,7 @@ public class ServiceInstances { // SERVICE REQUEST // Construct the default service name // TODO need to make this a configurable property - String defaultServiceModelName = getDefaultModel(servInstReq); + String defaultServiceModelName = requestHandlerUtils.getDefaultModel(servInstReq); RequestDetails requestDetails = servInstReq.getRequestDetails(); ModelInfo modelInfo = requestDetails.getModelInfo(); org.onap.so.db.catalog.beans.Service serviceRecord; @@ -1525,7 +1161,7 @@ public class ServiceInstances { } Recipe recipe = null; - String defaultSource = getDefaultModel(servInstReq); + String defaultSource = requestHandlerUtils.getDefaultModel(servInstReq); String modelCustomizationId = modelInfo.getModelCustomizationId(); String modelCustomizationName = modelInfo.getModelCustomizationName(); String relatedInstanceModelVersionId = null; @@ -1728,7 +1364,7 @@ public class ServiceInstances { private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) { - String defaultSource = getDefaultModel(sir); + String defaultSource = requestHandlerUtils.getDefaultModel(sir); VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString()); @@ -1742,7 +1378,7 @@ public class ServiceInstances { private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException { - String defaultNetworkType = getDefaultModel(sir); + String defaultNetworkType = requestHandlerUtils.getDefaultModel(sir); ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); String modelName = modelInfo.getModelName(); @@ -1777,40 +1413,7 @@ public class ServiceInstances { return recipe !=null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null; } - private Optional<String> retrieveModelName(RequestParameters requestParams) { - String requestTestApi = null; - TestApi testApi = null; - - if (requestParams != null) { - requestTestApi = requestParams.getTestApi(); - } - - if (requestTestApi == null) { - if(requestParams != null && requestParams.getALaCarte() != null && !requestParams.getALaCarte()) { - requestTestApi = env.getProperty(CommonConstants.MACRO_TEST_API); - } else { - requestTestApi = env.getProperty(CommonConstants.ALACARTE_TEST_API); - } - } - - try { - testApi = TestApi.valueOf(requestTestApi); - return Optional.of(testApi.getModelName()); - } catch (Exception e) { - logger.warn("Catching the exception on the valueOf enum call and continuing", e); - throw new IllegalArgumentException("Invalid TestApi is provided", e); - } - } - private String getDefaultModel(ServiceInstancesRequest sir) { - String defaultModel = sir.getRequestDetails().getRequestInfo().getSource() + "_DEFAULT"; - Optional<String> oModelName = retrieveModelName(sir.getRequestDetails().getRequestParameters()); - if (oModelName.isPresent()) { - defaultModel = oModelName.get(); - } - return defaultModel; - } - private Response configurationRecipeLookup(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { String serviceInstanceId = (instanceIdMap ==null)? null:instanceIdMap.get("serviceInstanceId"); Boolean aLaCarte = null; @@ -1820,26 +1423,26 @@ public class ServiceInstances { long startTime = System.currentTimeMillis (); ServiceInstancesRequest sir = null; - sir = convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri); - String requestScope = deriveRequestScope(action,sir, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri); + String requestScope = requestHandlerUtils.deriveRequestScope(action,sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject ( sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); if(sir.getRequestDetails().getRequestParameters() != null){ aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); } - parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq); - setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); + requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq); + requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName(); InfraActiveRequests dup = null; - dup = duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq); if(dup != null){ - inProgress = camundaHistoryCheck(dup, currentActiveReq); + inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (instanceIdMap != null && dup != null && inProgress) { - buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -1860,7 +1463,7 @@ public class ServiceInstances { ValidateException validateException = new ValidateException.Builder(error, HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR) .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; @@ -1903,7 +1506,7 @@ public class ServiceInstances { .setServiceInstanceId(serviceInstanceId) .setPnfCorrelationId(pnfCorrelationId) .setConfigurationId(configurationId) - .setRequestDetails(mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) .setApiVersion(apiVersion) .setALaCarte(aLaCarte) .setRequestUri(requestUri).build(); @@ -1913,80 +1516,7 @@ public class ServiceInstances { .errorInfo(errorLoggerInfo).build(); } - return postBPELRequest(currentActiveReq, requestClientParameter, orchestrationUri, requestScope); - } - - public String getRequestId(ContainerRequestContext requestContext) throws ValidateException { - String requestId = null; - if (requestContext.getProperty("requestId") != null) { - requestId = requestContext.getProperty("requestId").toString(); - } - if (UUIDChecker.isValidUUID(requestId)) { - return requestId; - } else { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) - .errorInfo(errorLoggerInfo).build(); - - throw validateException; - } - } - public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage) throws RequestDbFailureException{ - if ((status == Status.FAILED) || (status == Status.COMPLETE)) { - aq.setStatusMessage (errorMessage); - aq.setProgress(new Long(100)); - aq.setRequestStatus(status.toString()); - Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis()); - aq.setEndTime (endTimeStamp); - try{ - infraActiveRequestsClient.save(aq); - }catch(Exception e){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).build(); - } - } - } - protected String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag){ - String serviceType = null; - if(requestScope.equalsIgnoreCase(ModelType.service.toString())){ - String defaultServiceModelName = getDefaultModel(sir); - org.onap.so.db.catalog.beans.Service serviceRecord; - if(aLaCarteFlag){ - serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); - if(serviceRecord != null){ - serviceType = serviceRecord.getServiceType(); - } - }else{ - serviceRecord = catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId()); - if(serviceRecord != null){ - serviceType = serviceRecord.getServiceType(); - }else{ - serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); - if(serviceRecord != null){ - serviceType = serviceRecord.getServiceType(); - } - } - } - }else{ - serviceType = msoRequest.getServiceInstanceType(sir, requestScope); - } - return serviceType; - } - protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir){ - if(sir.getServiceInstanceId () != null){ - return sir.getServiceInstanceId (); - }else if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())){ - RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList(); - if(relatedInstances != null){ - for(RelatedInstanceList relatedInstanceList : relatedInstances){ - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - if(relatedInstance.getModelInfo().getModelType() == ModelType.service){ - return relatedInstance.getInstanceId(); - } - } - } - } - return null; - } + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, orchestrationUri, requestScope); + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java new file mode 100644 index 0000000000..695213bf20 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra.validation; + +import java.util.List; +import java.util.Map; + +import org.onap.so.exceptions.ValidationException; +import org.onap.so.serviceinstancebeans.CloudConfiguration; +import org.onap.so.serviceinstancebeans.RequestParameters; + +import com.google.common.base.Strings; + +public class CustomWorkflowValidation implements ValidationRule{ + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException{ + RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters(); + CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails ().getCloudConfiguration(); + String workflowUuid = info.getInstanceIdMap().get("workflowUuid"); + + if (cloudConfiguration == null) { + throw new ValidationException ("cloudConfiguration"); + }else if (Strings.isNullOrEmpty((cloudConfiguration.getCloudOwner ()))) { + throw new ValidationException ("cloudOwner"); + }else if (Strings.isNullOrEmpty((cloudConfiguration.getLcpCloudRegionId ()))) { + throw new ValidationException ("lcpCloudRegionId"); + }else if (Strings.isNullOrEmpty((cloudConfiguration.getTenantId ()))) { + throw new ValidationException ("tenantId"); + } + if(requestParameters == null){ + throw new ValidationException("requestParameters"); + } + + List<Map<String, Object>> userParams = requestParameters.getUserParams(); + if (!validateCustomUserParams(userParams, workflowUuid)) { + throw new ValidationException("userParams"); + } + return info; + } + + private boolean validateCustomUserParams(List<Map<String, Object>> userParams, String workflowUuid) { + return true; + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java new file mode 100644 index 0000000000..146062533e --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra; + + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import static org.onap.so.logger.MdcConstants.CLIENT_ID; + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.HttpHeadersConstants; +import org.onap.so.serviceinstancebeans.RequestReferences; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.util.ResourceUtils; +import org.springframework.web.util.UriComponentsBuilder; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class InstanceManagementTest extends BaseTest{ + + private final ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper errorMapper = new ObjectMapper(); + + @Autowired + private InstanceManagement instanceManagement; + + @Value("${wiremock.server.port}") + private String wiremockPort; + + private final String instanceManagementUri = "/onap/so/infra/instanceManagement/"; + + private String uri; + private URL selfLink; + private URL initialUrl; + private int initialPort; + private HttpHeaders headers; + + @Before + public void beforeClass() { + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); + // set headers + headers = new HttpHeaders(); + headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name"); + headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(CLIENT_ID, "VID"); + headers.set(REQUESTOR_ID, "xxxxxx"); + try { // generate one-time port number to avoid RANDOM port number later. + initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH)); + initialPort = initialUrl.getPort(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + stubFor(post(urlMatching(".*/infraActiveRequests.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + } + + public String inputStream(String JsonInput)throws IOException{ + JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput; + return new String(Files.readAllBytes(Paths.get(JsonInput))); + } + + private URL createExpectedSelfLink(String version, String requestId) { + System.out.println("createdUrl: " + initialUrl.toString()); + try { + selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId)); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + return selfLink; + } + + private String getWiremockResponseForCatalogdb(String file) { + try { + File resource= ResourceUtils.getFile("classpath:__files/catalogdb/"+file); + return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090","localhost:"+wiremockPort); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, HttpHeaders headers){ + + if (!headers.containsKey(HttpHeaders.ACCEPT)) { + headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + } + if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) { + headers.set(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON); + } + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort)); + + HttpEntity<String> request = new HttpEntity<>(requestJson, headers); + + return restTemplate.exchange(builder.toUriString(), + reqMethod, request, String.class); + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){ + return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders()); + } + + @Test + public void executeCustomWorkflow() throws IOException { + stubFor(post(urlPathEqualTo("/mso/async/services/VnfInPlaceUpdate")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]" + + "nfRole=GR-API-DEFAULT&action=inPlaceSoftwareUpdate")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeInPlaceUpdate_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + //expected response + ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); + RequestReferences requestReferences = new RequestReferences(); + requestReferences.setInstanceId("1882939"); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v1","32807a28-1a14-4b88-b7b3-2950918aa76d")); + expectedResponse.setRequestReferences(requestReferences); + uri = instanceManagementUri + "v1" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/workflows/71526781-e55c-4cb7-adb3-97e09d9c76be"; + ResponseEntity<String> response = sendRequest(inputStream("/ExecuteCustomWorkflow.json"), uri, HttpMethod.POST, headers); + + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java index ee98accfdc..d6fff7bdfb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java @@ -153,6 +153,27 @@ public class MsoRequestTest extends BaseTest { }); } @Test + @Parameters(method = "customWorkflowSuccessParameters") + public void customWorkflowSuccessTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, Action action, int reqVersion) throws ValidationException, IOException{ + this.sir = sir; + this.instanceIdMapTest = instanceIdMapTest; + this.action = action; + this.reqVersion = reqVersion; + this.version = "v" + reqVersion; + this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("workflowUuid", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + @Parameters + private Collection<Object[]> customWorkflowSuccessParameters() throws JsonParseException, JsonMappingException, IOException{ + return Arrays.asList(new Object[][]{ + {mapper.readValue(inputStream("/SuccessfulValidation/v1ExecuteCustomWorkflow.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "1"} + + }); + } + @Test @Parameters(method = "aLaCarteParameters") public void aLaCarteFlagTest(boolean expected, ServiceInstancesRequest sir) throws JsonParseException, IOException, ValidationException{ this.expected = expected; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java new file mode 100644 index 0000000000..b1a6e9f826 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java @@ -0,0 +1,331 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra; + + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import static org.onap.so.logger.MdcConstants.CLIENT_ID; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.MediaType; + +import org.apache.http.HttpStatus; +import org.junit.Before; + +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.logger.HttpHeadersConstants; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.onap.so.serviceinstancebeans.RequestInfo; +import org.onap.so.serviceinstancebeans.RequestParameters; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.util.UriComponentsBuilder; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class RequestHandlerUtilsTest extends BaseTest{ + + private final ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper errorMapper = new ObjectMapper(); + + @Autowired + private RequestHandlerUtils requestHandlerUtils; + + @Value("${wiremock.server.port}") + private String wiremockPort; + + private URL initialUrl; + private int initialPort; + private HttpHeaders headers; + + @Before + public void beforeClass() { + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); + // set headers + headers = new HttpHeaders(); + headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name"); + headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(CLIENT_ID, "VID"); + headers.set(REQUESTOR_ID, "xxxxxx"); + try { // generate one-time port number to avoid RANDOM port number later. + initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH)); + initialPort = initialUrl.getPort(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + stubFor(post(urlMatching(".*/infraActiveRequests.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + } + + public String inputStream(String JsonInput)throws IOException{ + JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput; + return new String(Files.readAllBytes(Paths.get(JsonInput))); + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, HttpHeaders headers){ + + if (!headers.containsKey(HttpHeaders.ACCEPT)) { + headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + } + if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) { + headers.set(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON); + } + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort)); + + HttpEntity<String> request = new HttpEntity<>(requestJson, headers); + + return restTemplate.exchange(builder.toUriString(), + reqMethod, request, String.class); + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){ + return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders()); + } + + @Test + public void test_mapJSONtoMSOStyle() throws IOException{ + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + String testRequest= inputStream("/ServiceInstanceDefault.json"); + String resultString = requestHandlerUtils.mapJSONtoMSOStyle(testRequest, null, false, null); + ServiceInstancesRequest sir = mapper.readValue(resultString, ServiceInstancesRequest.class); + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + assertEquals("f7ce78bb-423b-11e7-93f8-0050569a796",modelInfo.getModelCustomizationUuid()); + assertEquals("modelInstanceName",modelInfo.getModelInstanceName()); + assertEquals("f7ce78bb-423b-11e7-93f8-0050569a7965",modelInfo.getModelInvariantUuid()); + assertEquals("10",modelInfo.getModelUuid()); + + } + + + @Test + public void test_mapJSONtoMSOStyleUsePreload() throws IOException{ + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + String testRequest= inputStream("/ServiceInstanceDefault.json"); + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails rd = new RequestDetails(); + RequestParameters rp = new RequestParameters(); + rp.setUsePreload(true); + rd.setRequestParameters(rp); + sir.setRequestDetails(rd); + String resultString = requestHandlerUtils.mapJSONtoMSOStyle(testRequest, sir, false, null); + ServiceInstancesRequest sir1 = mapper.readValue(resultString, ServiceInstancesRequest.class); + assertTrue(sir1.getRequestDetails().getRequestParameters().getUsePreload()); + } + + @Test + public void setServiceTypeTestALaCarte() throws JsonProcessingException{ + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = true; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setSource("VID"); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceTypeALaCarte"); + + stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)) + .withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceTypeALaCarte"); + } + @Test + public void setServiceTypeTest() throws JsonProcessingException{ + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)) + .withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); + } + @Test + public void setServiceTypeTestDefault() throws JsonProcessingException{ + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)) + .withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); + } + @Test + public void setServiceTypeTestNetwork() throws JsonProcessingException{ + String requestScope = ModelType.network.toString(); + Boolean aLaCarteFlag = null; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelName("networkModelName"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "networkModelName"); + } + @Test + public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException{ + String requestScope = "instanceGroup"; + ServiceInstancesRequest sir = mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class); + assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc", requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + @Test + public void setServiceInstanceIdTest(){ + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f", requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + @Test + public void setServiceInstanceIdReturnNullTest(){ + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + assertNull(requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + @Test + public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException{ + stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertTrue(inProgress); + } + @Test + public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException{ + stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); + } + @Test + public void camundaHistoryCheckNotInProgressTest()throws ContactCamundaException, RequestDbFailureException{ + stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponseCompleted.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); + } + @Test + public void setCamundaHeadersTest()throws ContactCamundaException, RequestDbFailureException{ + String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password + String key = "07a7159d3bf51a0e53be7a8f89699be7"; + HttpHeaders headers = requestHandlerUtils.setCamundaHeaders(encryptedAuth, key); + List<org.springframework.http.MediaType> acceptedType = headers.getAccept(); + String expectedAcceptedType = "application/json"; + assertEquals(expectedAcceptedType, acceptedType.get(0).toString()); + String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION); + String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA=="; + assertEquals(expectedBasicAuth, basicAuth); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index 17fa011c93..639367074b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -29,9 +29,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID; @@ -63,20 +61,14 @@ import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; -import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.db.catalog.beans.Service; import org.onap.so.db.catalog.beans.ServiceRecipe; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.serviceinstancebeans.CloudConfiguration; -import org.onap.so.serviceinstancebeans.ModelInfo; -import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.RequestError; -import org.onap.so.serviceinstancebeans.RequestInfo; import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.serviceinstancebeans.RequestReferences; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; @@ -108,7 +100,7 @@ public class ServiceInstancesTest extends BaseTest{ @Autowired private ServiceInstances servInstances; - + @Value("${wiremock.server.port}") private String wiremockPort; @@ -190,39 +182,7 @@ public class ServiceInstancesTest extends BaseTest{ public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){ return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders()); } - - @Test - public void test_mapJSONtoMSOStyle() throws IOException{ - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - String testRequest= inputStream("/ServiceInstanceDefault.json"); - String resultString = servInstances.mapJSONtoMSOStyle(testRequest, null, false, null); - ServiceInstancesRequest sir = mapper.readValue(resultString, ServiceInstancesRequest.class); - ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); - assertEquals("f7ce78bb-423b-11e7-93f8-0050569a796",modelInfo.getModelCustomizationUuid()); - assertEquals("modelInstanceName",modelInfo.getModelInstanceName()); - assertEquals("f7ce78bb-423b-11e7-93f8-0050569a7965",modelInfo.getModelInvariantUuid()); - assertEquals("10",modelInfo.getModelUuid()); - - } - - - @Test - public void test_mapJSONtoMSOStyleUsePreload() throws IOException{ - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - String testRequest= inputStream("/ServiceInstanceDefault.json"); - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails rd = new RequestDetails(); - RequestParameters rp = new RequestParameters(); - rp.setUsePreload(true); - rd.setRequestParameters(rp); - sir.setRequestDetails(rd); - String resultString = servInstances.mapJSONtoMSOStyle(testRequest, sir, false, null); - ServiceInstancesRequest sir1 = mapper.readValue(resultString, ServiceInstancesRequest.class); - assertTrue(sir1.getRequestDetails().getRequestParameters().getUsePreload()); - } - + @Test public void createServiceInstanceVIDDefault() throws IOException{ TestAppender.events.clear(); @@ -2569,160 +2529,5 @@ public class ServiceInstancesTest extends BaseTest{ assertEquals(realResponse.getServiceException().getText(), "No valid modelCustomizationId for networkResourceCustomization lookup is specified"); } - @Test - public void setServiceTypeTestALaCarte() throws JsonProcessingException{ - String requestScope = ModelType.service.toString(); - Boolean aLaCarteFlag = true; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - requestInfo.setSource("VID"); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - Service defaultService = new Service(); - defaultService.setServiceType("testServiceTypeALaCarte"); - - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - String serviceType = servInstances.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "testServiceTypeALaCarte"); - } - @Test - public void setServiceTypeTest() throws JsonProcessingException{ - String requestScope = ModelType.service.toString(); - Boolean aLaCarteFlag = false; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - ModelInfo modelInfo = new ModelInfo(); - modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); - requestInfo.setSource("VID"); - requestDetails.setModelInfo(modelInfo); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - Service defaultService = new Service(); - defaultService.setServiceType("testServiceType"); - - stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - String serviceType = servInstances.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "testServiceType"); - } - @Test - public void setServiceTypeTestDefault() throws JsonProcessingException{ - String requestScope = ModelType.service.toString(); - Boolean aLaCarteFlag = false; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - ModelInfo modelInfo = new ModelInfo(); - modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); - requestInfo.setSource("VID"); - requestDetails.setModelInfo(modelInfo); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - Service defaultService = new Service(); - defaultService.setServiceType("testServiceType"); - - stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - String serviceType = servInstances.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "testServiceType"); - } - @Test - public void setServiceTypeTestNetwork() throws JsonProcessingException{ - String requestScope = ModelType.network.toString(); - Boolean aLaCarteFlag = null; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - ModelInfo modelInfo = new ModelInfo(); - modelInfo.setModelName("networkModelName"); - requestInfo.setSource("VID"); - requestDetails.setModelInfo(modelInfo); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - - String serviceType = servInstances.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "networkModelName"); - } - @Test - public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException{ - String requestScope = "instanceGroup"; - ServiceInstancesRequest sir = mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class); - assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc", servInstances.setServiceInstanceId(requestScope, sir)); - } - @Test - public void setServiceInstanceIdTest(){ - String requestScope = "vnf"; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f", servInstances.setServiceInstanceId(requestScope, sir)); - } - @Test - public void setServiceInstanceIdReturnNullTest(){ - String requestScope = "vnf"; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - assertNull(servInstances.setServiceInstanceId(requestScope, sir)); - } - @Test - public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException{ - stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/HistoryCheckResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - InfraActiveRequests duplicateRecord = new InfraActiveRequests(); - duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - boolean inProgress = false; - inProgress = servInstances.camundaHistoryCheck(duplicateRecord, null); - assertTrue(inProgress); - } - @Test - public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException{ - stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK))); - - InfraActiveRequests duplicateRecord = new InfraActiveRequests(); - duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - boolean inProgress = false; - inProgress = servInstances.camundaHistoryCheck(duplicateRecord, null); - assertFalse(inProgress); - } - @Test - public void camundaHistoryCheckNotInProgressTest()throws ContactCamundaException, RequestDbFailureException{ - stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/HistoryCheckResponseCompleted.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - InfraActiveRequests duplicateRecord = new InfraActiveRequests(); - duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - boolean inProgress = false; - inProgress = servInstances.camundaHistoryCheck(duplicateRecord, null); - assertFalse(inProgress); - } - @Test - public void setCamundaHeadersTest()throws ContactCamundaException, RequestDbFailureException{ - String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password - String key = "07a7159d3bf51a0e53be7a8f89699be7"; - HttpHeaders headers = servInstances.setCamundaHeaders(encryptedAuth, key); - List<org.springframework.http.MediaType> acceptedType = headers.getAccept(); - String expectedAcceptedType = "application/json"; - assertEquals(expectedAcceptedType, acceptedType.get(0).toString()); - String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION); - String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA=="; - assertEquals(expectedBasicAuth, basicAuth); - } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java new file mode 100644 index 0000000000..90c994fce0 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra.validation; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; + +import org.junit.Test; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.BaseTest; +import org.onap.so.exceptions.ValidationException; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class CustomWorkflowValidationTest extends BaseTest{ + + @Test + public void testCustomWorkflowValidation() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.inPlaceSoftwareUpdate, + 1, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vnf"); + + CustomWorkflowValidation validation = new CustomWorkflowValidation(); + validation.validate(info); + + assertEquals(info.getSir().getRequestDetails().getCloudConfiguration().getCloudOwner(), "att-aic"); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json new file mode 100644 index 0000000000..611ccb3c66 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json @@ -0,0 +1,18 @@ +{ + "requestDetails": { + "cloudConfiguration": { + "cloudOwner": "att-aic", + "lcpCloudRegionId": "mdt1", + "tenantId": "88a6ca3ee0394ade9403f075db23167e" + }, + "requestParameters": { + "userParams": [ + { + "existing_software_version": "3.1", + "new_software_version": "3.2", + "operations_timeout": "3600" + } + ] + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecuteCustomWorkflow.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecuteCustomWorkflow.json new file mode 100644 index 0000000000..611ccb3c66 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecuteCustomWorkflow.json @@ -0,0 +1,18 @@ +{ + "requestDetails": { + "cloudConfiguration": { + "cloudOwner": "att-aic", + "lcpCloudRegionId": "mdt1", + "tenantId": "88a6ca3ee0394ade9403f075db23167e" + }, + "requestParameters": { + "userParams": [ + { + "existing_software_version": "3.1", + "new_software_version": "3.2", + "operations_timeout": "3600" + } + ] + } + } +} |