diff options
Diffstat (limited to 'catalog-be/src/main/java/org/openecomp/sdc/be/tosca')
25 files changed, 4156 insertions, 4037 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java index 13356e5de4..f13331ed0b 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ArtifactTypes.java @@ -20,19 +20,19 @@ package org.openecomp.sdc.be.tosca; -import java.util.List; - import org.openecomp.sdc.generator.data.ArtifactType; +import java.util.List; + public class ArtifactTypes { - private List<ArtifactType> artifactTypes; + private List<ArtifactType> artifactTypes; - public List<ArtifactType> getArtifactTypes() { - return artifactTypes; - } + public List<ArtifactType> getArtifactTypes() { + return artifactTypes; + } - public void setArtifactTypes(List<ArtifactType> artifactTypes) { - this.artifactTypes = artifactTypes; - } + public void setArtifactTypes(List<ArtifactType> artifactTypes) { + this.artifactTypes = artifactTypes; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java deleted file mode 100644 index 7fecced358..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CSARTool.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * 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.openecomp.sdc.be.tosca; - -import org.openecomp.sdc.be.model.Component; - -public class CSARTool { - public static byte[] createCsar(Component component) { - - final String TOSCA_META_VERSION = "1.0"; - final String CSAR_VERSION = component.getCsarVersion(); - final String CREATED_BY = component.getCreatorFullName(); - final String ENTRY_DEFINITIONS = component.getNormalizedName(); - - /* - * StringBuilder builder = new StringBuilder(); try( FileOutputStream f = new FileOutputStream("test.zip"); ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(f)); ){ } - */ - - return null; - } - - public static String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { - final String BLOCK_0_TEMPLATE = "TOSCA-Meta-File-Version: %s"; - - return null; - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java index 886b654b81..4dbbf925d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CapabiltyRequirementConvertor.java @@ -20,50 +20,34 @@ package org.openecomp.sdc.be.tosca; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RequirementDefinition; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.tosca.ToscaUtils.SubstituitionEntry; -import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; -import org.openecomp.sdc.be.tosca.model.ToscaCapability; -import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaNodeType; -import org.openecomp.sdc.be.tosca.model.ToscaProperty; -import org.openecomp.sdc.be.tosca.model.ToscaRequirement; -import org.openecomp.sdc.be.tosca.model.ToscaTemplateCapability; +import org.openecomp.sdc.be.tosca.model.*; import org.openecomp.sdc.common.util.ValidationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import java.util.*; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.apache.commons.lang3.StringUtils.*; -import fj.data.Either; /** * Allows to convert requirements\capabilities of a component to requirements\capabilities of a substitution mappings section of a tosca template * @@ -71,502 +55,545 @@ import fj.data.Either; @org.springframework.stereotype.Component("capabilty-requirement-convertor") @Scope(value = "singleton") public class CapabiltyRequirementConvertor { - - private static final String NO_CAPABILITIES = "No Capabilities for node type"; - private static CapabiltyRequirementConvertor instance; - private static Logger logger = LoggerFactory.getLogger(CapabiltyRequirementConvertor.class.getName()); - public static final String PATH_DELIMITER = "."; - - @Autowired - private ToscaOperationFacade toscaOperationFacade; - - protected CapabiltyRequirementConvertor() {} - - public static synchronized CapabiltyRequirementConvertor getInstance() { - if (instance == null) { - instance = new CapabiltyRequirementConvertor(); - } - return instance; - } - /** - * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template - * @param componentInstance - * @param dataTypes - * @param nodeTemplate - * @return - */ - public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate) { - - Map<String, List<CapabilityDefinition>> capabilitiesInst = componentInstance.getCapabilities(); - if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) { - Map<String, ToscaTemplateCapability> capabilties = new HashMap<>(); - capabilitiesInst.entrySet().forEach(e -> { - List<CapabilityDefinition> capList = e.getValue(); - if (capList != null && !capList.isEmpty()) { - capList.forEach(c -> convertOverridenProperties(componentInstance, dataTypes, capabilties, c)); - } - }); - if (MapUtils.isNotEmpty(capabilties)) { - nodeTemplate.setCapabilities(capabilties); - } - } - return Either.left(nodeTemplate); - } - - private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c) { - if (CollectionUtils.isNotEmpty(c.getProperties())) { - c.getProperties() - .stream() - .filter(p -> p.getValue() != null || p.getDefaultValue() != null) - .forEach(p -> convertOverridenProperty(componentInstance, dataTypes, capabilties, c, p)); - } - } - - private void convertOverridenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c, ComponentInstanceProperty p) { - if (logger.isDebugEnabled()) { - logger.debug("Exist overriden property {} for capabity {} with value {}", p.getName(), c.getName(), p.getValue()); - } - ToscaTemplateCapability toscaTemplateCapability = capabilties.get(c.getName()); - if (toscaTemplateCapability == null) { - toscaTemplateCapability = new ToscaTemplateCapability(); - capabilties.put(c.getName(), toscaTemplateCapability); - } - Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties(); - if (toscaCapProp == null) { - toscaCapProp = new HashMap<>(); - } - Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p); - toscaCapProp.put(p.getName(), convertedValue); - toscaTemplateCapability.setProperties(toscaCapProp); - } - - private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) { - logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId()); - String propertyType = prop.getType(); - String innerType = null; - if (prop.getSchema() != null && prop.getSchema().getProperty() != null) { - innerType = prop.getSchema().getProperty().getType(); - } - String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue(); - return PropertyConvertor.getInstance().convertToToscaObject(propertyType, propValue, innerType, dataTypes); - } - /** - * Allows to convert requirements of a node type to tosca template requirements representation - * @param component - * @param nodeType - * @return - */ - public Either<ToscaNodeType, ToscaError> convertRequirements(Component component, ToscaNodeType nodeType) { - List<Map<String, ToscaRequirement>> toscaRequirements = convertRequirementsAsList(component); - if (!toscaRequirements.isEmpty()) { - nodeType.setRequirements(toscaRequirements); - } - logger.debug("Finish convert Requirements for node type"); - - return Either.left(nodeType); - } - - /** - * Allows to convert component requirements to the tosca template substitution mappings requirements - * @param componentsCache - * @param component - * @param substitutionMappings - * @return - */ - public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String,Component> componentsCache, Component component, SubstitutionMapping substitutionMappings) { - Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings); - Either<Map<String, String[]>, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component); - if(toscaRequirementsRes.isRight()){ - result = Either.right(toscaRequirementsRes.right().value()); - logger.error("Failed convert requirements for the component {}. ", component.getName()); - } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) { - substitutionMappings.setRequirements(toscaRequirementsRes.left().value()); - result = Either.left(substitutionMappings); - logger.debug("Finish convert requirements for the component {}. ", component.getName()); - } - return result; - } - - private List<Map<String, ToscaRequirement>> convertRequirementsAsList(Component component) { - Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); - List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>(); - if (requirements != null) { - for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) { - entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> { - ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, ModelConverter.isAtomicComponent(component), r); - Map<String, ToscaRequirement> requirement = new HashMap<>(); - - requirement.put(pair.left, pair.right); - toscaRequirements.add(requirement); - }); - logger.debug("Finish convert Requirements for node type"); - } - } else { - logger.debug("No Requirements for node type"); - } - return toscaRequirements; - } - - private boolean filter(Component component, String ownerId) { - return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null); - } - - private boolean isNodeTypeOwner(Component component, String ownerId) { - return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId); - } - - private String getSubPathByLastDelimiterAppearance(String path) { - return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1); - } - - private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache, Component component) { - Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); - Either<Map<String, String[]>, ToscaError> result; - if (requirements != null) { - result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements); - } else { - result = Either.left(Maps.newHashMap()); - logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName()); - } - return result; - } - - private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache, Component component, Map<String, List<RequirementDefinition>> requirements) { - - Map<String, String[]> toscaRequirements = new HashMap<>(); - Either<Map<String, String[]>, ToscaError> result = null; - for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) { - Optional<RequirementDefinition> failedToAddRequirement = entry.getValue() - .stream() - .filter(r->!addEntry(componentsCache, toscaRequirements, component, r.getName(), r.getParentName(), r.getPath())) - .findAny(); - if(failedToAddRequirement.isPresent()){ - logger.error("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ", - failedToAddRequirement.get().getName(), component.getName()); - result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); - } - logger.debug("Finish convert requirements for the component {}. ", component.getName()); - } - if(result == null){ - result = Either.left(toscaRequirements); - } - return result; - } - - private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache, Component component, Map<String, List<CapabilityDefinition>> capabilities) { - - Map<String, String[]> toscaRequirements = new HashMap<>(); - Either<Map<String, String[]>, ToscaError> result = null; - for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { - Optional<CapabilityDefinition> failedToAddRequirement = entry.getValue() - .stream() - .filter(c->!addEntry(componentsCache, toscaRequirements, component, c.getName(), c.getParentName(), c.getPath())) - .findAny(); - if(failedToAddRequirement.isPresent()){ - logger.error("Failed to convert capalility {} for substitution mappings section of a tosca template of the component {}. ", - failedToAddRequirement.get().getName(), component.getName()); - result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR); - } - logger.debug("Finish convert capalilities for the component {}. ", component.getName()); - } - if(result == null){ - result = Either.left(toscaRequirements); - } - return result; - } - - private boolean addEntry(Map<String,Component> componentsCache, Map<String, String[]> capReqMap, Component component, String name, String parentName, List<String> path){ - - SubstituitionEntry entry = new SubstituitionEntry(name, parentName, ""); - - if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, name, path, entry)){ - return false; - } - logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId()); - if (entry.getSourceName() != null) { - addEntry(capReqMap, component, path, entry); - } - logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName()); - return true; - - } - - private boolean shouldBuildSubstitutionName(Component component, List<String> path) { - return !ToscaUtils.isComplexVfc(component) && CollectionUtils.isNotEmpty(path) && path.iterator().hasNext(); - } - - private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, List<String> path, SubstituitionEntry entry) { - Optional<ComponentInstance> ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); - if(ci.isPresent()){ - Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, path, ci.get()); - if(buildSubstitutedName.isRight()){ - return false; - } - entry.setFullName(ci.get().getNormalizedName() + '.' + buildSubstitutedName.left().value()); - entry.setSourceName(buildSubstitutedName.left().value()); - } else { - return false; - } - return true; - } - - private void addEntry(Map<String, String[]> toscaRequirements, Component component, List<String> capPath, SubstituitionEntry entry) { - Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst(); - if (findFirst.isPresent()) { - entry.setOwner(findFirst.get().getNormalizedName()); - } - toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() }); - } - - private Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, String name, List<String> path, ComponentInstance instance) { - - Either<String, Boolean> result = null; - Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instance); - if(getOriginRes.isRight()){ - logger.debug("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid()); - result = Either.right(false); - } - if(result == null){ - List<String> reducedPath = getReducedPath(path); - reducedPath.remove(reducedPath.size()-1); - result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name); - } - return result; - } - - private String getRequirementPath(Component component, RequirementDefinition r) { - - // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) - // dirty quick fix. must be changed as capability redesign - List<String> capPath = r.getPath(); - String lastInPath = capPath.get(capPath.size() - 1); - Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); - if (findFirst.isPresent()) { - String lastInPathName = findFirst.get().getNormalizedName(); - - if (capPath.size() > 1) { - List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); - - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(r.getName()).toString(); - }else{ - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(r.getName()).toString(); - } - } - return ""; - } - - private ImmutablePair<String, ToscaRequirement> convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) { - String name = r.getName(); - if (!isNodeType) { - name = getRequirementPath(component, r); - } - logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId()); - ToscaRequirement toscaRequirement = new ToscaRequirement(); - - List<Object> occurences = new ArrayList<>(); - occurences.add(Integer.valueOf(r.getMinOccurrences())); - if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { - occurences.add(r.getMaxOccurrences()); - } else { - occurences.add(Integer.valueOf(r.getMaxOccurrences())); - } - toscaRequirement.setOccurrences(occurences); - toscaRequirement.setNode(r.getNode()); - toscaRequirement.setCapability(r.getCapability()); - toscaRequirement.setRelationship(r.getRelationship()); - - return new ImmutablePair<>(name, toscaRequirement); - } - - /** - * Allows to convert capabilities of a node type to tosca template capabilities - * @param component - * @param dataTypes - * @return - */ - public Map<String, ToscaCapability> convertCapabilities(Component component, Map<String, DataTypeDefinition> dataTypes) { - Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); - Map<String, ToscaCapability> toscaCapabilities = new HashMap<>(); - if (capabilities != null) { - boolean isNodeType = ModelConverter.isAtomicComponent(component); - for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { - entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes)); - } - } else { - logger.debug(NO_CAPABILITIES); - } - - return toscaCapabilities; - } - - /** - * Allows to convert capabilities of a server proxy node type to tosca template capabilities - * @param component - * @param proxyComponent - * @param instanceProxy - * @param dataTypes - * @return - */ - public Map<String, ToscaCapability> convertProxyCapabilities(Component component, Component proxyComponent, ComponentInstance instanceProxy, Map<String, DataTypeDefinition> dataTypes) { - Map<String, List<CapabilityDefinition>> capabilities = instanceProxy.getCapabilities(); - Map<String, ToscaCapability> toscaCapabilities = new HashMap<>(); - if (capabilities != null) { - boolean isNodeType = ModelConverter.isAtomicComponent(component); - for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { - entry.getValue().stream().forEach(c -> convertCapabilty(proxyComponent, toscaCapabilities, isNodeType, c, dataTypes)); - } - } else { - logger.debug(NO_CAPABILITIES); - } - - return toscaCapabilities; - } - - /** - * Allows to convert component capabilities to the tosca template substitution mappings capabilities - * @param componentsCache - * @param component - * @return - */ - public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache, Component component) { - Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); - Either<Map<String, String[]>, ToscaError> res; - if (capabilities != null) { - res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities); - } else { - res = Either.left(Maps.newHashMap()); - logger.debug(NO_CAPABILITIES); - } - return res; - } - - private String getCapabilityPath(CapabilityDefinition c, Component component) { - // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) - // dirty quick fix. must be changed as capability redesign - List<String> capPath = c.getPath(); - String lastInPath = capPath.get(capPath.size() - 1); - Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); - if (findFirst.isPresent()) { - String lastInPathName = findFirst.get().getNormalizedName(); - - if (capPath.size() > 1) { - List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); - - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(c.getName()).toString(); - }else{ - return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(c.getName()).toString(); - } - } - return ""; - } - - private void convertCapabilty(Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes) { - String name = c.getName(); - if (!isNodeType) { - name = getCapabilityPath(c, component); - } - logger.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId()); - ToscaCapability toscaCapability = new ToscaCapability(); - toscaCapability.setDescription(c.getDescription()); - toscaCapability.setType(c.getType()); - - List<Object> occurences = new ArrayList<>(); - occurences.add(Integer.valueOf(c.getMinOccurrences())); - if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { - occurences.add(c.getMaxOccurrences()); - } else { - occurences.add(Integer.valueOf(c.getMaxOccurrences())); - } - toscaCapability.setOccurrences(occurences); - - toscaCapability.setValid_source_types(c.getValidSourceTypes()); - List<ComponentInstanceProperty> properties = c.getProperties(); - if (CollectionUtils.isNotEmpty(properties)) { - Map<String, ToscaProperty> toscaProperties = new HashMap<>(); - for (PropertyDefinition property : properties) { - ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); - toscaProperties.put(property.getName(), toscaProperty); - } - toscaCapability.setProperties(toscaProperties); - } - toscaCapabilities.put(name, toscaCapability); - } - /** - * Allows to build substituted name of capability\requirement of the origin component instance according to the path - * @param componentsCache - * @param originComponent - * @param path - * @param name - * @return - */ - public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path, String name) { - StringBuilder substitutedName = new StringBuilder(); - boolean nameBuiltSuccessfully = true; - Either<String, Boolean> result; - if(CollectionUtils.isNotEmpty(path) && !ToscaUtils.isComplexVfc(originComponent)){ - List<String> reducedPath = getReducedPath(path); - Collections.reverse(reducedPath); - nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName); - } - if(nameBuiltSuccessfully){ - result = Either.left(substitutedName.append(name).toString()); - } else { - result = Either.right(nameBuiltSuccessfully); - } - return result; - } - - private List<String> getReducedPath(List<String> path) { - List<String> pathCopy = Lists.newArrayList(); - path.stream().forEach(id -> {if(!pathCopy.contains(id))pathCopy.add(id);}); - return pathCopy; - } - - private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName) { - if(CollectionUtils.isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && !ToscaUtils.isComplexVfc(originComponent)){ - String instanceId = instanceIdIter.next(); - Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); - if(!instanceOpt.isPresent()){ - logger.debug("Failed to find an instance with uniqueId {} on a component with uniqueId {}", instanceId, originComponent.getUniqueId()); - return false; - } - substitutedName.append(instanceOpt.get().getNormalizedName()).append('.'); - Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instanceOpt.get()); - if(getOriginRes.isRight()){ - return false; - } - appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName); - } - return true; - } - - Either<Component, Boolean> getOriginComponent(Map<String, Component> componentsCache, ComponentInstance instance) { - Either<Component, Boolean> result; - Either<Component, StorageOperationStatus> getOriginRes; - if(componentsCache.containsKey(instance.getActualComponentUid())){ - result = Either.left(componentsCache.get(instance.getActualComponentUid())); - } else { - ComponentParametersView filter = getFilter(instance); - getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter); - if(getOriginRes.isRight()){ - logger.debug("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid()); - result = Either.right(false); - } else { - result = Either.left(getOriginRes.left().value()); - componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value()); - } - } - return result; - } - - private ComponentParametersView getFilter(ComponentInstance instance) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstances(false); - if(instance.getIsProxy()){ - filter.setIgnoreCapabilities(false); - filter.setIgnoreRequirements(false); - } - return filter; - } - -} + + private static final String NO_CAPABILITIES = "No Capabilities for node type"; + private static CapabiltyRequirementConvertor instance; + private static final Logger logger = LoggerFactory.getLogger(CapabiltyRequirementConvertor.class); + public static final String PATH_DELIMITER = "."; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + + protected CapabiltyRequirementConvertor() {} + + public static synchronized CapabiltyRequirementConvertor getInstance() { + if (instance == null) { + instance = new CapabiltyRequirementConvertor(); + } + return instance; + } + + public String buildCapabilityNameForComponentInstance( Map<String,Component> componentCache , ComponentInstance componentInstance, CapabilityDefinition c) { + + Either eitherName = buildSubstitutedName(componentCache, c.getName(), c.getPath(), c.getOwnerId(), componentInstance); + + return eitherName.isLeft() ? (String) eitherName.left().value() : c.getName() ; + } + + + /** + * Allows to convert capabilities of a component to capabilities of a substitution mappings section of a tosca template + * @param componentInstance + * @param dataTypes + * @param nodeTemplate + * @return + */ + public Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceCapabilties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, ToscaNodeTemplate nodeTemplate) { + + Map<String, List<CapabilityDefinition>> capabilitiesInst = componentInstance.getCapabilities(); + Map<String,Component> componentCache = new HashMap<>(); + if (capabilitiesInst != null && !capabilitiesInst.isEmpty()) { + Map<String, ToscaTemplateCapability> capabilities = new HashMap<>(); + capabilitiesInst.entrySet().forEach( e -> { + List<CapabilityDefinition> capList = e.getValue(); + if ( capList != null && !capList.isEmpty() ) { + capList.forEach( c -> { + String capName = buildCapabilityNameForComponentInstance( componentCache , componentInstance , c ) ; + convertOverridenProperties( componentInstance, dataTypes, capabilities, c , capName ); + } ); + } + }); + if (MapUtils.isNotEmpty(capabilities)) { + nodeTemplate.setCapabilities(capabilities); + } + } + return Either.left(nodeTemplate); + } + + private void convertOverridenProperties(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, CapabilityDefinition c , String capabilityName) { + if (isNotEmpty(c.getProperties())) { + c.getProperties() + .stream() + .filter(p -> p.getValue() != null || p.getDefaultValue() != null) + .forEach(p -> convertOverridenProperty(componentInstance, dataTypes, capabilties , p ,capabilityName)); + } + } + + private void convertOverridenProperty(ComponentInstance componentInstance, Map<String, DataTypeDefinition> dataTypes, Map<String, ToscaTemplateCapability> capabilties, ComponentInstanceProperty p ,String capabilityName) { + if (logger.isDebugEnabled()) { + logger.debug("Exist overriden property {} for capabity {} with value {}", p.getName(), capabilityName, p.getValue()); + } + ToscaTemplateCapability toscaTemplateCapability = capabilties.computeIfAbsent( capabilityName , key -> new ToscaTemplateCapability() ); + + Map<String, Object> toscaCapProp = toscaTemplateCapability.getProperties(); + if (toscaCapProp == null) { + toscaCapProp = new HashMap<>(); + } + Object convertedValue = convertInstanceProperty(dataTypes, componentInstance, p); + toscaCapProp.put(p.getName(), convertedValue); + toscaTemplateCapability.setProperties(toscaCapProp); + } + + private Object convertInstanceProperty(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, ComponentInstanceProperty prop) { + logger.debug("Convert property {} for instance {}", prop.getName(), componentInstance.getUniqueId()); + String propertyType = prop.getType(); + String innerType = null; + if (prop.getSchema() != null && prop.getSchema().getProperty() != null) { + innerType = prop.getSchema().getProperty().getType(); + } + String propValue = prop.getValue() == null ? prop.getDefaultValue() : prop.getValue(); + return PropertyConvertor.getInstance().convertToToscaObject(propertyType, propValue, innerType, dataTypes); + } + /** + * Allows to convert requirements of a node type to tosca template requirements representation + * @param component + * @param nodeType + * @return + */ + public Either<ToscaNodeType, ToscaError> convertRequirements(Component component, ToscaNodeType nodeType) { + List<Map<String, ToscaRequirement>> toscaRequirements = convertRequirementsAsList(component); + if (!toscaRequirements.isEmpty()) { + nodeType.setRequirements(toscaRequirements); + } + logger.debug("Finish convert Requirements for node type"); + + return Either.left(nodeType); + } + + /** + * Allows to convert component requirements to the tosca template substitution mappings requirements + * @param componentsCache + * @param component + * @param substitutionMappings + * @return + */ + public Either<SubstitutionMapping, ToscaError> convertSubstitutionMappingRequirements(Map<String,Component> componentsCache, Component component, SubstitutionMapping substitutionMappings) { + Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings); + Either<Map<String, String[]>, ToscaError> toscaRequirementsRes = convertSubstitutionMappingRequirementsAsMap(componentsCache, component); + if(toscaRequirementsRes.isRight()){ + result = Either.right(toscaRequirementsRes.right().value()); + logger.error("Failed convert requirements for the component {}. ", component.getName()); + } else if (MapUtils.isNotEmpty(toscaRequirementsRes.left().value())) { + substitutionMappings.setRequirements(toscaRequirementsRes.left().value()); + result = Either.left(substitutionMappings); + logger.debug("Finish convert requirements for the component {}. ", component.getName()); + } + return result; + } + + private List<Map<String, ToscaRequirement>> convertRequirementsAsList(Component component) { + Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); + List<Map<String, ToscaRequirement>> toscaRequirements = new ArrayList<>(); + if (requirements != null) { + for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) { + entry.getValue().stream().filter(r -> filter(component, r.getOwnerId())).forEach(r -> { + ImmutablePair<String, ToscaRequirement> pair = convertRequirement(component, ModelConverter.isAtomicComponent(component), r); + Map<String, ToscaRequirement> requirement = new HashMap<>(); + + requirement.put(pair.left, pair.right); + toscaRequirements.add(requirement); + }); + logger.debug("Finish convert Requirements for node type"); + } + } else { + logger.debug("No Requirements for node type"); + } + return toscaRequirements; + } + + private boolean filter(Component component, String ownerId) { + return !ModelConverter.isAtomicComponent(component) || isNodeTypeOwner(component, ownerId) || (ModelConverter.isAtomicComponent(component) && ownerId == null); + } + + private boolean isNodeTypeOwner(Component component, String ownerId) { + return ModelConverter.isAtomicComponent(component) && component.getUniqueId().equals(ownerId); + } + + private String getSubPathByLastDelimiterAppearance(String path) { + return path.substring(path.lastIndexOf(PATH_DELIMITER) + 1); + } + + private String dropLast( String path, String delimiter ) { + if (isBlank(path) || isBlank(delimiter)){ + return path; + } + return path.substring(0, path.lastIndexOf(delimiter)); + } + + private Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingRequirementsAsMap(Map<String, Component> componentsCache, Component component) { + Map<String, List<RequirementDefinition>> requirements = component.getRequirements(); + Either<Map<String, String[]>, ToscaError> result; + if (requirements != null) { + result = buildAddSubstitutionMappingsRequirements(componentsCache, component, requirements); + } else { + result = Either.left(Maps.newHashMap()); + logger.debug("No requirements for substitution mappings section of a tosca template of the component {}. ", component.getName()); + } + return result; + } + + private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsRequirements(Map<String, Component> componentsCache, Component component, Map<String, List<RequirementDefinition>> requirements) { + + Map<String, String[]> toscaRequirements = new HashMap<>(); + Either<Map<String, String[]>, ToscaError> result = null; + for (Map.Entry<String, List<RequirementDefinition>> entry : requirements.entrySet()) { + Optional<RequirementDefinition> failedToAddRequirement = entry.getValue() + .stream() + .filter(r->!addEntry(componentsCache, toscaRequirements, component, r.getName(), r.getParentName(), r.getOwnerId(), r.getPath())) + .findAny(); + if(failedToAddRequirement.isPresent()){ + logger.error("Failed to convert requirement {} for substitution mappings section of a tosca template of the component {}. ", + failedToAddRequirement.get().getName(), component.getName()); + result = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + } + logger.debug("Finish convert requirements for the component {}. ", component.getName()); + } + if(result == null){ + result = Either.left(toscaRequirements); + } + return result; + } + + private Either<Map<String, String[]>, ToscaError> buildAddSubstitutionMappingsCapabilities(Map<String, Component> componentsCache, Component component, Map<String, List<CapabilityDefinition>> capabilities) { + + Map<String, String[]> toscaRequirements = new HashMap<>(); + Either<Map<String, String[]>, ToscaError> result = null; + for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { + Optional<CapabilityDefinition> failedToAddRequirement = entry.getValue() + .stream() + .filter(c->!addEntry(componentsCache, toscaRequirements, component, c.getName(), c.getParentName(), c.getOwnerId(), c.getPath())) + .findAny(); + if(failedToAddRequirement.isPresent()){ + logger.error("Failed to convert capalility {} for substitution mappings section of a tosca template of the component {}. ", + failedToAddRequirement.get().getName(), component.getName()); + result = Either.right(ToscaError.NODE_TYPE_CAPABILITY_ERROR); + } + logger.debug("Finish convert capalilities for the component {}. ", component.getName()); + } + if(result == null){ + result = Either.left(toscaRequirements); + } + return result; + } + + private boolean addEntry(Map<String,Component> componentsCache, Map<String, String[]> capReqMap, Component component, String name, String parentName, String ownerId, List<String> path){ + + SubstituitionEntry entry = new SubstituitionEntry(name, parentName, ""); + + if(shouldBuildSubstitutionName(component, path) && !buildSubstitutedNamePerInstance(componentsCache, component, name, path, ownerId, entry)){ + return false; + } + logger.debug("The requirement/capability {} belongs to the component {} ", entry.getFullName(), component.getUniqueId()); + if (entry.getSourceName() != null) { + addEntry(capReqMap, component, path, entry); + } + logger.debug("Finish convert the requirement/capability {} for the component {}. ", entry.getFullName(), component.getName()); + return true; + + } + + private boolean shouldBuildSubstitutionName(Component component, List<String> path) { + return !ToscaUtils.isComplexVfc(component) && isNotEmpty(path) && path.iterator().hasNext(); + } + + private boolean buildSubstitutedNamePerInstance(Map<String, Component> componentsCache, Component component, String name, List<String> path, String ownerId, SubstituitionEntry entry) { + Optional<ComponentInstance> ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); + if(!ci.isPresent()){ + logger.error("Failed to find ci in the path is {} component {}", path, component.getUniqueId()); + + Collections.reverse(path); + + logger.error("try to reverse path {} component {}", path, component.getUniqueId()); + ci = component.getComponentInstances().stream().filter(c->c.getUniqueId().equals(Iterables.getLast(path))).findFirst(); + } + if(ci.isPresent()){ + Either<String, Boolean> buildSubstitutedName = buildSubstitutedName(componentsCache, name, path, ownerId, ci.get()); + if(buildSubstitutedName.isRight()){ + logger.error("Failed buildSubstitutedName name {} path {} component {}", name, path, component.getUniqueId()); + return false; + } + entry.setFullName(ci.get().getNormalizedName() + '.' + buildSubstitutedName.left().value()); + entry.setSourceName(buildSubstitutedName.left().value()); + } else { + logger.error("Failed to find ci in the path is {} component {}", path, component.getUniqueId()); + return false; + } + return true; + } + + private void addEntry(Map<String, String[]> toscaRequirements, Component component, List<String> capPath, SubstituitionEntry entry) { + Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(Iterables.getLast(capPath))).findFirst(); + if (findFirst.isPresent()) { + entry.setOwner(findFirst.get().getNormalizedName()); + } + toscaRequirements.put(entry.getFullName(), new String[] { entry.getOwner(), entry.getSourceName() }); + } + + public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, String name, List<String> path, String ownerId, ComponentInstance instance) { + + Either<String, Boolean> result = null; + Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instance); + if(getOriginRes.isRight()){ + logger.error("Failed to build substituted name for the capability/requirement {}. Failed to get an origin component with uniqueId {}", name, instance.getComponentUid()); + result = Either.right(false); + } + if(result == null){ + List<String> reducedPath = ownerId !=null ? getReducedPathByOwner(path , ownerId ) : getReducedPath(path) ; + logger.debug("reducedPath for ownerId {}, reducedPath {} ", ownerId, reducedPath); + reducedPath.remove(reducedPath.size()-1); + result = buildSubstitutedName(componentsCache, getOriginRes.left().value(), reducedPath, name); + } + return result; + } + + private String getRequirementPath(Component component, RequirementDefinition r) { + + // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) + // dirty quick fix. must be changed as capability redesign + List<String> capPath = r.getPath(); + String lastInPath = capPath.get(capPath.size() - 1); + Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); + if (findFirst.isPresent()) { + String lastInPathName = findFirst.get().getNormalizedName(); + + if (capPath.size() > 1) { + List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); + + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(r.getName()).toString(); + }else{ + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(r.getName()).toString(); + } + } + return ""; + } + + private ImmutablePair<String, ToscaRequirement> convertRequirement(Component component, boolean isNodeType, RequirementDefinition r) { + String name = r.getName(); + if (!isNodeType) { + name = getRequirementPath(component, r); + } + logger.debug("the requirement {} belongs to resource {} ", name, component.getUniqueId()); + ToscaRequirement toscaRequirement = new ToscaRequirement(); + + List<Object> occurences = new ArrayList<>(); + occurences.add(Integer.valueOf(r.getMinOccurrences())); + if (r.getMaxOccurrences().equals(RequirementDataDefinition.MAX_OCCURRENCES)) { + occurences.add(r.getMaxOccurrences()); + } else { + occurences.add(Integer.valueOf(r.getMaxOccurrences())); + } + toscaRequirement.setOccurrences(occurences); + toscaRequirement.setNode(r.getNode()); + toscaRequirement.setCapability(r.getCapability()); + toscaRequirement.setRelationship(r.getRelationship()); + + return new ImmutablePair<>(name, toscaRequirement); + } + + /** + * Allows to convert capabilities of a node type to tosca template capabilities + * @param component + * @param dataTypes + * @return + */ + public Map<String, ToscaCapability> convertCapabilities(Component component, Map<String, DataTypeDefinition> dataTypes) { + Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); + Map<String, ToscaCapability> toscaCapabilities = new HashMap<>(); + if (capabilities != null) { + boolean isNodeType = ModelConverter.isAtomicComponent(component); + for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { + entry.getValue().stream().filter(c -> filter(component, c.getOwnerId())).forEach(c -> convertCapabilty(component, toscaCapabilities, isNodeType, c, dataTypes , c.getName())); + } + } else { + logger.debug(NO_CAPABILITIES); + } + + return toscaCapabilities; + } + + /** + * Allows to convert capabilities of a server proxy node type to tosca template capabilities + * @param component + * @param proxyComponent + * @param instanceProxy + * @param dataTypes + * @return + */ + public Map<String, ToscaCapability> convertProxyCapabilities(Map<String, Component> componentCache, Component component, Component proxyComponent, ComponentInstance instanceProxy, Map<String, DataTypeDefinition> dataTypes) { + Map<String, List<CapabilityDefinition>> capabilities = instanceProxy.getCapabilities(); + Map<String, ToscaCapability> toscaCapabilities = new HashMap<>(); + if (capabilities != null) { + boolean isNodeType = ModelConverter.isAtomicComponent(component); + for (Map.Entry<String, List<CapabilityDefinition>> entry : capabilities.entrySet()) { + entry.getValue().stream().forEach(c -> convertCapabilty(proxyComponent, toscaCapabilities, isNodeType, c, dataTypes , buildCapabilityNameForComponentInstance( componentCache , instanceProxy , c ))); + } + } else { + logger.debug(NO_CAPABILITIES); + } + + return toscaCapabilities; + } + + /** + * Allows to convert component capabilities to the tosca template substitution mappings capabilities + * @param componentsCache + * @param component + * @return + */ + public Either<Map<String, String[]>, ToscaError> convertSubstitutionMappingCapabilities(Map<String, Component> componentsCache, Component component) { + Map<String, List<CapabilityDefinition>> capabilities = component.getCapabilities(); + Either<Map<String, String[]>, ToscaError> res; + if (capabilities != null) { + res = buildAddSubstitutionMappingsCapabilities(componentsCache, component, capabilities); + } else { + res = Either.left(Maps.newHashMap()); + logger.debug(NO_CAPABILITIES); + } + return res; + } + + private String getCapabilityPath(CapabilityDefinition c, Component component) { + // Evg : for the last in path take real instance name and not "decrypt" unique id. ( instance name can be change and not equal to id..) + // dirty quick fix. must be changed as capability redesign + List<String> capPath = c.getPath(); + String lastInPath = capPath.get(capPath.size() - 1); + Optional<ComponentInstance> findFirst = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(lastInPath)).findFirst(); + if (findFirst.isPresent()) { + String lastInPathName = findFirst.get().getNormalizedName(); + + if (capPath.size() > 1) { + List<String> pathArray = Lists.reverse(capPath.stream().map(path -> ValidationUtils.normalizeComponentInstanceName(getSubPathByLastDelimiterAppearance(path))).collect(Collectors.toList())); + + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(String.join(PATH_DELIMITER, pathArray.subList(1, pathArray.size() ))).append(PATH_DELIMITER).append(c.getName()).toString(); + }else{ + return new StringBuilder().append(lastInPathName).append(PATH_DELIMITER).append(c.getName()).toString(); + } + } + return ""; + } + + private void convertCapabilty(Component component, Map<String, ToscaCapability> toscaCapabilities, boolean isNodeType, CapabilityDefinition c, Map<String, DataTypeDefinition> dataTypes , String capabilityName) { + String name = isNoneBlank(capabilityName) ? capabilityName : c.getName(); + if (!isNodeType) { + name = getCapabilityPath(c, component); + } + logger.debug("the capabilty {} belongs to resource {} ", name, component.getUniqueId()); + ToscaCapability toscaCapability = new ToscaCapability(); + toscaCapability.setDescription(c.getDescription()); + toscaCapability.setType(c.getType()); + + List<Object> occurences = new ArrayList<>(); + occurences.add(Integer.valueOf(c.getMinOccurrences())); + if (c.getMaxOccurrences().equals(CapabilityDataDefinition.MAX_OCCURRENCES)) { + occurences.add(c.getMaxOccurrences()); + } else { + occurences.add(Integer.valueOf(c.getMaxOccurrences())); + } + toscaCapability.setOccurrences(occurences); + + toscaCapability.setValid_source_types(c.getValidSourceTypes()); + List<ComponentInstanceProperty> properties = c.getProperties(); + if (isNotEmpty(properties)) { + Map<String, ToscaProperty> toscaProperties = new HashMap<>(); + for (PropertyDefinition property : properties) { + ToscaProperty toscaProperty = PropertyConvertor.getInstance().convertProperty(dataTypes, property, true); + toscaProperties.put(property.getName(), toscaProperty); + } + toscaCapability.setProperties(toscaProperties); + } + toscaCapabilities.put(name, toscaCapability); + } + /** + * Allows to build substituted name of capability\requirement of the origin component instance according to the path + * @param componentsCache + * @param originComponent + * @param path + * @param name + * @return + */ + public Either<String, Boolean> buildSubstitutedName(Map<String, Component> componentsCache, Component originComponent, List<String> path, String name) { + StringBuilder substitutedName = new StringBuilder(); + boolean nameBuiltSuccessfully = true; + Either<String, Boolean> result; + if(isNotEmpty(path) && !ToscaUtils.isComplexVfc(originComponent)){ + List<String> reducedPath = getReducedPath(path); + Collections.reverse(reducedPath); + nameBuiltSuccessfully = appendNameRecursively(componentsCache, originComponent, reducedPath.iterator(), substitutedName); + } + if(nameBuiltSuccessfully){ + result = Either.left(substitutedName.append(name).toString()); + } else { + result = Either.right(nameBuiltSuccessfully); + } + return result; + } + + protected List<String> getReducedPathByOwner(List<String> path , String ownerId) { + logger.debug("ownerId {}, path {} ", ownerId, path); + if ( CollectionUtils.isEmpty(path) ){ + logger.debug("cannot perform reduce by owner, path to component is empty"); + return path; + } + if ( isBlank(ownerId) ){ + logger.debug("cannot perform reduce by owner, component owner is empty"); + return path; + } + //reduce by owner + Map map = path.stream().collect( Collectors.toMap( it -> dropLast(it,PATH_DELIMITER) , Function.identity() , ( a , b ) -> a.endsWith(ownerId) ? a : b )); + //reduce list&duplicates and preserve order + return path.stream().distinct().filter(it -> map.values().contains(it) ).collect(Collectors.toList()); + } + + private List<String> getReducedPath(List<String> path) { + return path.stream().distinct().collect(Collectors.toList()); + } + + private boolean appendNameRecursively(Map<String, Component> componentsCache, Component originComponent, Iterator<String> instanceIdIter, StringBuilder substitutedName) { + if(isNotEmpty(originComponent.getComponentInstances()) && instanceIdIter.hasNext() && !ToscaUtils.isComplexVfc(originComponent)){ + String instanceId = instanceIdIter.next(); + Optional<ComponentInstance> instanceOpt = originComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst(); + if(!instanceOpt.isPresent()){ + logger.error("Failed to find an instance with uniqueId {} on a component with uniqueId {}", instanceId, originComponent.getUniqueId()); + return false; + } + substitutedName.append(instanceOpt.get().getNormalizedName()).append('.'); + Either<Component, Boolean> getOriginRes = getOriginComponent(componentsCache, instanceOpt.get()); + if(getOriginRes.isRight()){ + return false; + } + appendNameRecursively(componentsCache, getOriginRes.left().value(), instanceIdIter, substitutedName); + } + return true; + } + + Either<Component, Boolean> getOriginComponent(Map<String, Component> componentsCache, ComponentInstance instance) { + Either<Component, Boolean> result; + Either<Component, StorageOperationStatus> getOriginRes; + if(componentsCache.containsKey(instance.getActualComponentUid())){ + result = Either.left(componentsCache.get(instance.getActualComponentUid())); + } else { + ComponentParametersView filter = getFilter(instance); + getOriginRes = toscaOperationFacade.getToscaElement(instance.getActualComponentUid(), filter); + if(getOriginRes.isRight()){ + logger.error("Failed to get an origin component with uniqueId {}", instance.getActualComponentUid()); + result = Either.right(false); + } else { + result = Either.left(getOriginRes.left().value()); + componentsCache.put(getOriginRes.left().value().getUniqueId(), getOriginRes.left().value()); + } + } + return result; + } + + private ComponentParametersView getFilter(ComponentInstance instance) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + if(instance.getIsProxy()){ + filter.setIgnoreCapabilities(false); + filter.setIgnoreRequirements(false); + filter.setIgnoreCategories(false); + } + return filter; + } + +}
\ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java index f6ae79b26a..ed3a2462bd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/CsarUtils.java @@ -103,1458 +103,1466 @@ import fj.data.Either; */ @org.springframework.stereotype.Component("csar-utils") public class CsarUtils { - private static Logger log = LoggerFactory.getLogger(CsarUtils.class.getName()); - - @Autowired - private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; - @Autowired - private ArtifactCassandraDao artifactCassandraDao; - @Autowired - private ComponentsUtils componentsUtils; - @Autowired - private ToscaExportHandler toscaExportUtils; - @Autowired - private ArtifactsBusinessLogic artifactsBusinessLogic; - @Autowired - protected ToscaOperationFacade toscaOperationFacade; - - - @javax.annotation.Resource - private ServiceBusinessLogic serviceBusinessLogic; - - private Gson gson = new Gson(); - - public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); - public static final String SDC_VERSION = ExternalConfiguration.getAppVersion(); - - public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0"); - public static final String ARTIFACTS_PATH = "Artifacts/"; - public static final String RESOURCES_PATH = "Resources/"; - public static final String INFORMATIONAL_ARTIFACTS = "Informational/"; - public static final String DEPLOYMENT_ARTIFACTS = "Deployment/"; - - public static final String DEFINITIONS_PATH = "Definitions/"; - private static final String CSAR_META_VERSION = "1.0"; - private static final String CSAR_META_PATH_FILE_NAME = "csar.meta"; - private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; - private static final String TOSCA_META_VERSION = "1.0"; - private static final String CSAR_VERSION = "1.1"; - public static final String ARTIFACTS = "Artifacts"; - public static final String DEFINITION = "Definitions"; - public static final String DEL_PATTERN = "([/\\\\]+)"; - private static String versionFirstThreeOctates; - - public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + - ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - "([\\d\\w\\_\\-\\.\\s]+)"; - - public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+ - // Artifact Group (i.e Deployment/Informational) - "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - // Artifact Type - "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + - // Artifact Any File Name - ".+"; - public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)"; + private static final Logger log = LoggerFactory.getLogger(CsarUtils.class); + + @Autowired + private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao; + @Autowired + private ArtifactCassandraDao artifactCassandraDao; + @Autowired + private ComponentsUtils componentsUtils; + @Autowired + private ToscaExportHandler toscaExportUtils; + @Autowired + private ArtifactsBusinessLogic artifactsBusinessLogic; + @Autowired + protected ToscaOperationFacade toscaOperationFacade; + + + @javax.annotation.Resource + private ServiceBusinessLogic serviceBusinessLogic; + + private Gson gson = new Gson(); + + public static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); + public static final String SDC_VERSION = ExternalConfiguration.getAppVersion(); + + public static final Pattern UUID_NORMATIVE_NEW_VERSION = Pattern.compile("^\\d{1,}.0"); + public static final String ARTIFACTS_PATH = "Artifacts/"; + public static final String RESOURCES_PATH = "Resources/"; + public static final String INFORMATIONAL_ARTIFACTS = "Informational/"; + public static final String DEPLOYMENT_ARTIFACTS = "Deployment/"; + + public static final String DEFINITIONS_PATH = "Definitions/"; + private static final String CSAR_META_VERSION = "1.0"; + private static final String CSAR_META_PATH_FILE_NAME = "csar.meta"; + private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta"; + private static final String TOSCA_META_VERSION = "1.0"; + private static final String CSAR_VERSION = "1.1"; + public static final String ARTIFACTS = "Artifacts"; + public static final String DEFINITION = "Definitions"; + public static final String DEL_PATTERN = "([/\\\\]+)"; + private static String versionFirstThreeOctates; + + public static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN + + ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + "([\\d\\w\\_\\-\\.\\s]+)"; + + public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+ + // Artifact Group (i.e Deployment/Informational) + "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + // Artifact Type + "([\\w\\_\\-\\.\\s]+)" + DEL_PATTERN + + // Artifact Any File Name + ".+"; + public static final String VALID_ENGLISH_ARTIFACT_NAME = "([\\w\\_\\-\\.\\s]+)"; public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+ // Service Template File Name "([\\w\\_\\-\\.\\s]+)"; public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar"; - public CsarUtils() { - if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ - Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); - matcher.find(); - versionFirstThreeOctates = matcher.group(0); - } else { - versionFirstThreeOctates = ""; - } - } - - /** - * - * @param component - * @param getFromCS - * @param isInCertificationRequest - * @return - */ - public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) { - return createCsar(component, getFromCS, isInCertificationRequest, false); - } - - private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { - final String createdBy = component.getCreatorFullName(); - - String fileName; - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - fileName = artifactDefinition.getArtifactName(); - - String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); - String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel); - byte[] csarBlock0Byte = csarBlock0.getBytes(); - - final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName); - byte[] toscaBlock0Byte = toscaBlock0.getBytes(); - - Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator); - - if (generateCsarZipResponse.isRight()) { - return Either.right(generateCsarZipResponse.right().value()); - } - - return Either.left(generateCsarZipResponse.left().value()); - } - - private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { - try ( - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ZipOutputStream zip = new ZipOutputStream(out); - ){ - zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME)); - zip.write(csarBlock0Byte); - zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME)); - zip.write(toscaBlock0Byte); - Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator); - if (populateZip.isRight()) { - log.debug("Failed to populate CSAR zip file {}", populateZip.right().value()); - return Either.right(populateZip.right().value()); - } - - zip.finish(); - byte[] byteArray = out.toByteArray(); - - return Either.left(byteArray); - } catch (IOException e) { - log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e); - - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); - return Either.right(responseFormat); - } - } - - private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException { - - LifecycleStateEnum lifecycleState = component.getLifecycleState(); - String componentYaml; - Either<ToscaRepresentation, ToscaError> exportComponent; - byte[] mainYaml; - // <file name, cassandraId, component> - List<Triple<String, String, Component>> dependencies = null; - List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>(); - - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - String fileName = artifactDefinition.getArtifactName(); - - if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { - String cassandraId = artifactDefinition.getEsId(); - Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); - if (fromCassandra.isRight()) { + public CsarUtils() { + if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){ + Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION); + matcher.find(); + versionFirstThreeOctates = matcher.group(0); + } else { + versionFirstThreeOctates = ""; + } + } + + /** + * + * @param component + * @param getFromCS + * @param isInCertificationRequest + * @return + */ + public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) { + return createCsar(component, getFromCS, isInCertificationRequest, false); + } + + private Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { + final String createdBy = component.getCreatorFullName(); + + String fileName; + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + fileName = artifactDefinition.getArtifactName(); + + String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel(); + String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel); + byte[] csarBlock0Byte = csarBlock0.getBytes(); + + final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName); + byte[] toscaBlock0Byte = toscaBlock0.getBytes(); + + Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest, mockGenerator); + + if (generateCsarZipResponse.isRight()) { + return Either.right(generateCsarZipResponse.right().value()); + } + + return Either.left(generateCsarZipResponse.left().value()); + } + + private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest, boolean mockGenerator) { + try ( + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(out); + ){ + zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME)); + zip.write(csarBlock0Byte); + zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME)); + zip.write(toscaBlock0Byte); + Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest, mockGenerator); + if (populateZip.isRight()) { + log.debug("Failed to populate CSAR zip file {}", populateZip.right().value()); + return Either.right(populateZip.right().value()); + } + + zip.finish(); + byte[] byteArray = out.toByteArray(); + + return Either.left(byteArray); + } catch (IOException e) { + log.debug("Failed with IOexception to create CSAR zip for component {}", component.getUniqueId(), e); + + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + return Either.right(responseFormat); + } + } + + private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest, boolean mockGenerator) throws IOException { + + LifecycleStateEnum lifecycleState = component.getLifecycleState(); + String componentYaml; + Either<ToscaRepresentation, ToscaError> exportComponent; + byte[] mainYaml; + // <file name, cassandraId, component> + List<Triple<String, String, Component>> dependencies = null; + List<ImmutablePair<Component, byte[]>> generatorInputs = new LinkedList<>(); + + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + String fileName = artifactDefinition.getArtifactName(); + + if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) { + String cassandraId = artifactDefinition.getEsId(); + Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); + if (fromCassandra.isRight()) { log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value()); - return Either.right(responseFormat); - } - mainYaml = fromCassandra.left().value(); - - } else { - exportComponent = toscaExportUtils.exportComponent(component); - if (exportComponent.isRight()) { - log.debug("exportComponent failed", exportComponent.right().value()); - ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError); - return Either.right(responseFormat); - } - ToscaRepresentation exportResult = exportComponent.left().value(); - componentYaml = exportResult.getMainYaml(); - mainYaml = componentYaml.getBytes(); - dependencies = exportResult.getDependencies(); - } - - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); - zip.write(mainYaml); - //US798487 - Abstraction of complex types - if (!ModelConverter.isAtomicComponent(component)){ - log.debug("Component {} is complex - generating abstract type for it..", component.getName()); - writeComponentInterface(component, zip, fileName); - } - - generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml)); - - if (dependencies == null) { - Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component); - if (dependenciesRes.isRight()) { - log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), - dependenciesRes.right().value()); - ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value()); - ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); - return Either.right(responseFormat); - } - dependencies = dependenciesRes.left().value().getDependencies(); - } - - //UID <cassandraId,filename,component> - Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>(); - - if (dependencies != null && !dependencies.isEmpty()) { - for (Triple<String, String, Component> d : dependencies) { - String cassandraId = d.getMiddle(); - Component childComponent = d.getRight(); - Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent); - - if (entryData.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); - return Either.right(responseFormat); - } - - //fill innerComponentsCache - fileName = d.getLeft(); - addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent); - addInnerComponentsToCache(innerComponentsCache, childComponent); - - byte[] content = entryData.left().value(); - generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content)); - } - - //add inner components to CSAR - for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) { - - ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue(); - - Component innerComponent = innerComponentTriple.getRight(); - String icFileName = innerComponentTriple.getMiddle(); - - // add component to zip - Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); - if (entryData.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); - log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(), - entryData.right().value()); - return Either.right(responseFormat); - } - byte[] content = entryData.left().value(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); - zip.write(content); - - // add component interface to zip - if (!ModelConverter.isAtomicComponent(innerComponent)) { - writeComponentInterface(innerComponent, zip, icFileName); - } - } - } - - //retrieve SDC.zip from Cassandra - Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); - - if(latestSchemaFilesFromCassandra.isRight()){ - log.error("Error retrieving SDC Schema files from cassandra" ); - return Either.right(latestSchemaFilesFromCassandra.right().value()); - } - - //add files from retireved SDC.zip to Definitions folder in CSAR - Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value()); - - if(addSchemaFilesFromCassandra.isRight()){ - return addSchemaFilesFromCassandra; - } - - // Artifact Generation - if (component.getComponentType() == ComponentTypeEnum.SERVICE - && isInCertificationRequest) { - - List<ArtifactDefinition> aiiArtifactList; - - Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs); - - if (handleAAIArtifacts.isLeft()) { - aiiArtifactList = handleAAIArtifacts.left().value(); - } else { - log.debug("AAI Artifacts handling failed"); - return Either.right(handleAAIArtifacts.right().value()); - } - - if (isInCertificationRequest) { - Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel( - component, aiiArtifactList, false, true); - - if (handleAllAAIArtifactsInDataModel.isRight()) { - log.debug("AAI Artifacts handling (create, update, delete) failed"); - return Either.right(handleAllAAIArtifactsInDataModel.right().value()); - } - } - - } - - Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component); - - if (collectedComponentCsarDefinition.isRight()) { - return Either.right(collectedComponentCsarDefinition.right().value()); - } - - return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); - } - - private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){ - - final int initSize = 2048; - - log.debug("Starting copy from Schema file zip to CSAR zip"); - - try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { - - ZipEntry entry = null; - - while ((entry = zipStream.getNextEntry()) != null) { - - String entryName = entry.getName(); - int readSize = initSize; - byte[] entryData = new byte[initSize]; - - while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { - bos.write(entryData, 0, readSize); - } - - bos.flush(); - out.flush(); - zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); - zip.write(out.toByteArray()); - zip.flush(); - out.reset(); - } - } catch (IOException e) { - log.error("Error while writing the SDC schema file to the CSAR {}", e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - log.debug("Finished coppy from Schema file zip to CSAR zip"); - - return Either.left(zip); - } - - - private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, - Component childComponent) { - - List<ComponentInstance> instances = childComponent.getComponentInstances(); - - if(instances != null) { - instances.forEach(ci -> { - ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid()); - if (componentRecord == null) { - // all resource must be only once! - Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid()); - if (resource.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } - Component componentRI = resource.left().value(); - - Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts(); - ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - if (childArtifactDefinition != null) { - //add to cache - addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI); - } - - //if not atomic - insert inner components as well - if(!ModelConverter.isAtomicComponent(componentRI)) { - addInnerComponentsToCache(componentCache, componentRI); - } - } - }); - } - } - - private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, - String id, String fileName, Component component) { - - ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID()); - if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) { - componentCache.put(component.getInvariantUUID(), - new ImmutableTriple<String, String, Component>(id, fileName, component)); - - if(cachedComponent != null) { - //overwriting component with newer version - log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion()); - } - } - } - - private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) { - try { - Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component); - ToscaRepresentation componentInterfaceYaml = componentInterface.left().value(); - String mainYaml = componentInterfaceYaml.getMainYaml(); - String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName); - - zip.putNextEntry(new ZipEntry(interfaceFileName)); - zip.write(mainYaml.getBytes()); - - } catch (Exception e) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - - return Either.left(zip); - } - - private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) { - - ComponentTypeEnum componentType = component.getComponentType(); - List<Artifact> generatedArtifacts; - List<ArtifactDefinition> aaiArtifacts = new LinkedList<>(); - - if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) { - List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs); - - Either<List<Artifact>, String> generatorResponse; - - if (mockGenerator) { - generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component); - } else { - generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component); - } - - if (generatorResponse.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value()); - return Either.right(responseFormat); - } - - generatedArtifacts = generatorResponse.left().value(); - - aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts); - - } - - return Either.left(aaiArtifacts); - } - - private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) { - - Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse; - User lastComponentUpdater; - - List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component); - List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component); - List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component); - - String lastUpdaterUserId = component.getLastUpdaterUserId(); - Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true); - - if (validateUserExists.isRight()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found"); - return Either.right(responseFormat); - } - - lastComponentUpdater = validateUserExists.left().value(); - - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Delete), lastComponentUpdater, shouldLock, - inTransaction); - - if (handleAAIArtifactsResponse.isRight()) { - return handleAAIArtifactsResponse; - } - - handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Create), lastComponentUpdater, shouldLock, - inTransaction); - - if (handleAAIArtifactsResponse.isRight()) { - return handleAAIArtifactsResponse; - } - - return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Update), lastComponentUpdater, shouldLock, inTransaction); - } - - private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) { - - Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet(); - Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet(); - - return artifactsFromAAI.stream() - .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())) - .filter(e -> checkAaiForUpdate(component, e)) - .collect(Collectors.toList()); - } - - private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) { - ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel()); - - if (artifactDefinitionComp == null) { - log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel()); - return false; - } - - // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated - if (artifactDefinitionComp.getGenerated() == null) { - if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) { - return true; - } else { - log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel()); - } - } else { - if (artifactDefinition.getGenerated()) { - return true; - } else { - log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel()); - } - } - return false; - } - - private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) { - - Set<String> aaiLabels = artifactsFromAAI.stream() - .map(ArtifactDefinition::getArtifactLabel) - .collect(Collectors.toSet()); - - List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream() - // Filter Out Artifacts that are not contained in artifacts returned - // from AAI API - .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - - List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream() - // Filter Out Artifacts that are not contained in artifacts returned - // from AAI API - .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - - artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational); - - return artifactsForDeleteDeployment.stream() - .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))) - .collect(Collectors.toList()); - } - - private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) { - - Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet(); - Set<String> componentInfoLabels = component.getArtifacts().keySet(); - - // If the artifact label does not exist in the service - - // store the artifact (generate uuid and version, "generated" flag is TRUE) - return artifactsFromAAI.stream() - .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())) - .collect(Collectors.toList()); - } - - private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock, - boolean inTransaction) { - - String componentUniqueId = component.getUniqueId(); - ComponentTypeEnum componentType = component.getComponentType(); - - for (ArtifactDefinition artDef : generatedArtifactsDefinitions) { - String data = gson.toJson(artDef); - String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data); - String artifactUniqueId = null; - - if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Update) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.Delete)) { - String artifactLabel = artDef.getArtifactLabel(); - ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel); - if (artifactDefinition != null) { - artifactUniqueId = artifactDefinition.getUniqueId(); - } - } - - Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null, - null, null, user, component, shouldLock, inTransaction, false); - - if (validateAndHandleArtifact.isRight()) { - if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.Update == operationType.getArtifactOperationEnum()) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString()); - - Either.right(responseFormat); - } else { - log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel()); - } - } - } - - return Either.left(ActionStatus.OK); - } - - private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) { - List<ArtifactDefinition> artifactDefList = new LinkedList<>(); - - for (Artifact artifact : generatorOutput) { - ArtifactDefinition newEntry = new ArtifactDefinition(); - newEntry.setArtifactName(artifact.getName()); - newEntry.setArtifactType(artifact.getType()); - newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType())); - newEntry.setDescription(artifact.getDescription()); - - // Normalizing the artifact label to match those stored in DB - String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel()); - newEntry.setArtifactLabel(normalizeArtifactLabel); - newEntry.setPayload(Base64.decodeBase64(artifact.getPayload())); - newEntry.setArtifactChecksum(artifact.getChecksum()); - // Flag that set to true in case that the artifact is generated by AI&I generator - newEntry.setGenerated(Boolean.TRUE); - - artifactDefList.add(newEntry); - } - - return artifactDefList; - } - - // List<ImmutablePair<Component, byte[] artifactBytes>> - // artifact stored by label - private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) { - List<Artifact> listOfArtifactsInput = new LinkedList<>(); - for (ImmutablePair<Component, byte[]> triple : inputs) { - Component component = triple.getLeft(); - - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - - String artifactName = artifactDefinition.getArtifactName(); - String artifactType = artifactDefinition.getArtifactType(); - String artifactGroupType = artifactDefinition.getArtifactGroupType().getType(); - String artifactDescription = artifactDefinition.getDescription(); - String artifactLabel = artifactDefinition.getArtifactLabel(); - byte[] right = triple.getRight(); - // The md5 calculated on the uncoded data - String md5Hex = DigestUtils.md5Hex(right); - byte[] payload = Base64.encodeBase64(right); - String artifactVersion = artifactDefinition.getArtifactVersion(); - - Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload); - convertedArtifact.setName(artifactName); - convertedArtifact.setDescription(artifactDescription); - convertedArtifact.setLabel(artifactLabel); - convertedArtifact.setVersion(artifactVersion); - - listOfArtifactsInput.add(convertedArtifact); - } - - return listOfArtifactsInput; - } - - private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) { - byte[] content; - if (cassandraId == null || cassandraId.isEmpty()) { - Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent); - if (exportRes.isRight()) { - log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value()); - return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value())); - } - content = exportRes.left().value().getMainYaml().getBytes(); - } else { - Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); - if (fromCassandra.isRight()) { - return Either.right(fromCassandra.right().value()); - } else { - content = fromCassandra.left().value(); - } - } - return Either.left(content); - } - - private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() { - Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); - - if(specificSchemaFiles.isRight()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); - ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); - return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); - } - - List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value(); - - if(listOfSchemas.isEmpty()){ - log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL)); - } - - SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); - - return Either.left(schemaFile.getPayloadAsArray()); - } - - private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) { - Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId); - - if (artifactResponse.isRight()) { - log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value()); - - StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value()); - ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); - return Either.right(convertedFromStorageResponse); - } - ESArtifactData artifactData = artifactResponse.left().value(); - return Either.left(artifactData.getDataAsArray()); - } - - private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { - final String BLOCK_0_TEMPLATE = - "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; - String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel); - return readyBlock; - } - - private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { - final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n"; - return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef); - } - - private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) { - - ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl(); - ArtifactTypes artifactTypes = new ArtifactTypes(); - List<ArtifactType> artifactTypesList = new LinkedList<>(); - ArtifactType otherType; - - if (type == null) { - otherType = ArtifactType.OTHER; - } else { - otherType = type; - } - - artifactTypesList.add(otherType); - artifactTypes.setArtifactTypes(artifactTypesList); - - String configJson = gson.toJson(artifactTypes); - Map<String, String> additionalParams = new HashMap<>(); - String version; - - if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) { - version = component.getVersion(); - } else { - String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); - Integer majorVersion = Integer.parseInt(versionParts[0]); - - version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0"; - } - - additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); - GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams); - - Map<String, List<String>> errorData = generatedArtifacts.getErrorData(); - - if (!errorData.isEmpty()) { - Set<String> keySet = errorData.keySet(); - StringBuilder error = new StringBuilder(); - - for (String key : keySet) { - List<String> errorList = errorData.get(key); - log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList); - error.append(key + errorList); - } - - return Either.right(error.toString()); - } - - return Either.left(generatedArtifacts.getResultData()); - } - - /** - * Extracts artifacts of VFCs from CSAR - * - * @param csar - * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace - */ - public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) { - - Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>(); - if (csar != null) { - log.debug("************* Going to extract VFCs artifacts from Csar. "); - Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); - csar.entrySet().stream() - // filter CSAR entry by node type artifact path - .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) - // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path - .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts)); - // add counter suffix to artifact labels - handleWarningMessages(collectedWarningMessages); - - } - return artifacts; - } - - /** - * Print warnings to log - * - * @param collectedWarningMessages - */ - public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) { - collectedWarningMessages.entrySet().stream() - // for each vfc - .forEach(e -> e.getValue().stream() - // add each warning message to log - .forEach(args -> log.warn(e.getKey(), args.toArray()))); - - } - - private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) { - if (extractedVfcArtifact != null) { - List<ArtifactDefinition> currArtifactsList; - String vfcToscaNamespace = extractedVfcArtifact.getKey(); - if (artifacts.containsKey(vfcToscaNamespace)) { - currArtifactsList = artifacts.get(vfcToscaNamespace); - } else { - currArtifactsList = new ArrayList<>(); - artifacts.put(vfcToscaNamespace, currArtifactsList); - } - currArtifactsList.add(extractedVfcArtifact.getValue()); - } - } - - private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) { - ArtifactDefinition artifact; - String[] parsedCsarArtifactPath = entry.getKey().split("/"); - Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages); - if (eitherArtifactGroupType.isLeft()) { - artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value()); - } else { - return null; - } - return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact); - } - - private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) { - Either<ArtifactGroupTypeEnum, Boolean> result; - try { - ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase()); - if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) { - String warningMessage = "Warning - unrecognized artifact group type {} was received."; - List<String> messageArguments = new ArrayList<>(); - messageArguments.add(groupType); - if (!collectedWarningMessages.containsKey(warningMessage)) { - Set<List<String>> messageArgumentLists = new HashSet<>(); - messageArgumentLists.add(messageArguments); - collectedWarningMessages.put(warningMessage, messageArgumentLists); - } else { - collectedWarningMessages.get(warningMessage).add(messageArguments); - } - - result = Either.right(false); - } else { - - result = Either.left(artifactGroupType); - } - } catch (Exception e) { - log.debug("detectArtifactGroupType failed with exception", e); - result = Either.right(false); - } - return result; - } - - private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) { - ArtifactDefinition artifact; - artifact = new ArtifactDefinition(); - artifact.setArtifactGroupType(artifactGroupType); - artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages)); - artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1])); - artifact.setPayloadData(Base64.encodeBase64String(entry.getValue())); - artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName()); - artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName())); - artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR); - artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue())); - return artifact; - } - - public static final class NonMetaArtifactInfo { - private final String path; - private final String artifactName; - private final String displayName; - private final String artifactLabel; - private final ArtifactTypeEnum artifactType; - private final ArtifactGroupTypeEnum artifactGroupType; - private String payloadData; - private String artifactChecksum; - private String artifactUniqueId; - - public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId) { - super(); - this.path = path; - this.artifactName = ValidationUtils.normalizeFileName(artifactName); - this.artifactType = artifactType; - this.artifactGroupType = artifactGroupType; - final int pointIndex = artifactName.lastIndexOf('.'); - if (pointIndex > 0) { - displayName = artifactName.substring(0, pointIndex); - } else { - displayName = artifactName; - } - this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName); - if (payloadData != null) { - this.payloadData = Base64.encodeBase64String(payloadData); - this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); - } - this.artifactUniqueId = artifactUniqueId; - } - - public String getPath() { - return path; - } - - public String getArtifactName() { - return artifactName; - } - - public ArtifactTypeEnum getArtifactType() { - return artifactType; - } - - public String getDisplayName() { - return displayName; - } - - public ArtifactGroupTypeEnum getArtifactGroupType() { - return artifactGroupType; - } - - public String getArtifactLabel() { - return artifactLabel; - } - - public String getPayloadData() { - return payloadData; - } - - public String getArtifactChecksum() { - return artifactChecksum; - } - - public String getArtifactUniqueId() { - return artifactUniqueId; - } - - public void setArtifactUniqueId(String artifactUniqueId) { - this.artifactUniqueId = artifactUniqueId; - } - - } - - /** - * This method checks the artifact GroupType & Artifact Type. <br> - * if there is any problem warning messages are added to collectedWarningMessages - * - * @param artifactPath - * @param collectedWarningMessages - * @return - */ - public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) { - Either<NonMetaArtifactInfo, Boolean> ret; - try { - String[] parsedArtifactPath = artifactPath.split("/"); - // Validate Artifact Group Type - Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages); - if (eitherGroupType.isLeft()) { - final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value(); - - // Validate Artifact Type - String artifactType = parsedArtifactPath[2]; - artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages); - - String artifactFileNameType = parsedArtifactPath[3]; - ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null)); - - } else { - ret = Either.right(eitherGroupType.right().value()); - } - } catch (Exception e) { - log.debug("detectArtifactGroupType failed with exception", e); - ret = Either.right(false); - } - return ret; - - } - - private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) { - String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized."; - return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName); - } - - private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) { - String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized."; - return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages); - } - - private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) { - - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName); - Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null; - - if(artifactGroupType != null){ - switch (artifactGroupType) { - case INFORMATIONAL: - resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - .getResourceInformationalArtifacts(); - break; - case DEPLOYMENT: - resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() - .getResourceDeploymentArtifacts(); - break; - default: - break; - } - } - - Set<String> validArtifactTypes = null; - if(resourceValidTypeArtifacts != null){ - validArtifactTypes = resourceValidTypeArtifacts.keySet(); - } - - if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) { - List<String> messageArguments = new ArrayList<>(); - messageArguments.add(receivedTypeName); - messageArguments.addAll(Arrays.asList(arguments)); - if (!collectedWarningMessages.containsKey(warningMessage)) { - Set<List<String>> messageArgumentLists = new HashSet<>(); - messageArgumentLists.add(messageArguments); - collectedWarningMessages.put(warningMessage, messageArgumentLists); - } else { - collectedWarningMessages.get(warningMessage).add(messageArguments); - } - } - - return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType(); - } - - private Either<ZipOutputStream, ResponseFormat> writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{ - ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); - - Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedtPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); - } - - ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); - writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedtPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); - } - - Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts(); - Set<String> keySet = componentInstancesArtifacts.keySet(); - - String currentPath = ARTIFACTS_PATH + RESOURCES_PATH; - for (String keyAssetName : keySet) { - ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName); - String pathWithAssetName = currentPath + keyAssetName + "/"; - writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeComponentArtifactsToSpecifiedtPath.isRight()){ - return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); - } - } - - return Either.left(zipstream); - } - - private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, - String currentPath, boolean isInCertificationRequest) throws IOException { - Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); - //Keys are defined: - //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>. - //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0" - Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet(); - for (String keyAssetName : componentTypeArtifactsKeys) { - ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName); - ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts(); - String pathWithAssetName = currentPath + keyAssetName + "/"; - Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); - - if(writeArtifactsInfoToSpecifiedtPath.isRight()){ - return writeArtifactsInfoToSpecifiedtPath; - } - } - - return Either.left(zipstream); - } - - private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException { - Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo - .getArtifactsInfo(); - Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet(); - - for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) { - String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/"; - - Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); - Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet(); - - for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) { - List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum); - String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/"; - - Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest); - - if(writeArtifactDefinition.isRight()){ - return writeArtifactDefinition; - } - } - } - - return Either.left(zip); - } - - private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList, - String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException { - - ComponentTypeEnum componentType = mainComponent.getComponentType(); - String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType(); - - for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { - if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE - && artifactDefinition.getArtifactType().equals(heatEnvType) || + return Either.right(responseFormat); + } + mainYaml = fromCassandra.left().value(); + + } else { + exportComponent = toscaExportUtils.exportComponent(component); + if (exportComponent.isRight()) { + log.debug("exportComponent failed", exportComponent.right().value()); + ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError); + return Either.right(responseFormat); + } + ToscaRepresentation exportResult = exportComponent.left().value(); + componentYaml = exportResult.getMainYaml(); + mainYaml = componentYaml.getBytes(); + dependencies = exportResult.getDependencies(); + } + + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName)); + zip.write(mainYaml); + //US798487 - Abstraction of complex types + if (!ModelConverter.isAtomicComponent(component)){ + log.debug("Component {} is complex - generating abstract type for it..", component.getName()); + writeComponentInterface(component, zip, fileName); + } + + generatorInputs.add(new ImmutablePair<Component, byte[]>(component, mainYaml)); + + if (dependencies == null) { + Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component); + if (dependenciesRes.isRight()) { + log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), + dependenciesRes.right().value()); + ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value()); + ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError); + return Either.right(responseFormat); + } + dependencies = dependenciesRes.left().value().getDependencies(); + } + + //UID <cassandraId,filename,component> + Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>(); + + if (dependencies != null && !dependencies.isEmpty()) { + for (Triple<String, String, Component> d : dependencies) { + String cassandraId = d.getMiddle(); + Component childComponent = d.getRight(); + Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent); + + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); + return Either.right(responseFormat); + } + + //fill innerComponentsCache + fileName = d.getLeft(); + addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent); + addInnerComponentsToCache(innerComponentsCache, childComponent); + + byte[] content = entryData.left().value(); + generatorInputs.add(new ImmutablePair<Component, byte[]>(childComponent, content)); + } + + //add inner components to CSAR + for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) { + + ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue(); + + Component innerComponent = innerComponentTriple.getRight(); + String icFileName = innerComponentTriple.getMiddle(); + + // add component to zip + Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent); + if (entryData.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value()); + log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(), + entryData.right().value()); + return Either.right(responseFormat); + } + byte[] content = entryData.left().value(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName)); + zip.write(content); + + // add component interface to zip + if (!ModelConverter.isAtomicComponent(innerComponent)) { + writeComponentInterface(innerComponent, zip, icFileName); + } + } + } + + //retrieve SDC.zip from Cassandra + Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra(); + + if(latestSchemaFilesFromCassandra.isRight()){ + log.error("Error retrieving SDC Schema files from cassandra" ); + return Either.right(latestSchemaFilesFromCassandra.right().value()); + } + + //add files from retireved SDC.zip to Definitions folder in CSAR + Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra = addSchemaFilesFromCassandra(zip, latestSchemaFilesFromCassandra.left().value()); + + if(addSchemaFilesFromCassandra.isRight()){ + return addSchemaFilesFromCassandra; + } + + // Artifact Generation + if (component.getComponentType() == ComponentTypeEnum.SERVICE + && isInCertificationRequest) { + + List<ArtifactDefinition> aiiArtifactList; + + Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts = handleAAIArtifacts(component, mockGenerator, generatorInputs); + + if (handleAAIArtifacts.isLeft()) { + aiiArtifactList = handleAAIArtifacts.left().value(); + } else { + log.debug("AAI Artifacts handling failed"); + return Either.right(handleAAIArtifacts.right().value()); + } + + if (isInCertificationRequest) { + Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel = handleAllAAIArtifactsInDataModel( + component, aiiArtifactList, false, true); + + if (handleAllAAIArtifactsInDataModel.isRight()) { + log.debug("AAI Artifacts handling (create, update, delete) failed"); + return Either.right(handleAllAAIArtifactsInDataModel.right().value()); + } + } + + } + + Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component); + + if (collectedComponentCsarDefinition.isRight()) { + return Either.right(collectedComponentCsarDefinition.right().value()); + } + + return writeAllFilesToScar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest); + } + + private Either<ZipOutputStream, ResponseFormat> addSchemaFilesFromCassandra(ZipOutputStream zip, byte[] schemaFileZip){ + + final int initSize = 2048; + + log.debug("Starting copy from Schema file zip to CSAR zip"); + + try (ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BufferedOutputStream bos = new BufferedOutputStream(out, initSize);) { + + ZipEntry entry = null; + + while ((entry = zipStream.getNextEntry()) != null) { + + String entryName = entry.getName(); + int readSize = initSize; + byte[] entryData = new byte[initSize]; + + while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) { + bos.write(entryData, 0, readSize); + } + + bos.flush(); + out.flush(); + zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName)); + zip.write(out.toByteArray()); + zip.flush(); + out.reset(); + } + } catch (IOException e) { + log.error("Error while writing the SDC schema file to the CSAR {}", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + log.debug("Finished coppy from Schema file zip to CSAR zip"); + + return Either.left(zip); + } + + + private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, + Component childComponent) { + + List<ComponentInstance> instances = childComponent.getComponentInstances(); + + if(instances != null) { + instances.forEach(ci -> { + ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid()); + if (componentRecord == null) { + // all resource must be only once! + Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid()); + if (resource.isRight()) { + log.debug("Failed to fetch resource with id {} for instance {}"); + } + Component componentRI = resource.left().value(); + + Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts(); + ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + if (childArtifactDefinition != null) { + //add to cache + addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI); + } + + //if not atomic - insert inner components as well + if(!ModelConverter.isAtomicComponent(componentRI)) { + addInnerComponentsToCache(componentCache, componentRI); + } + } + }); + } + } + + private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache, + String id, String fileName, Component component) { + + ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID()); + if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) { + componentCache.put(component.getInvariantUUID(), + new ImmutableTriple<String, String, Component>(id, fileName, component)); + + if(cachedComponent != null) { + //overwriting component with newer version + log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion()); + } + } + } + + private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip, String fileName) { + try { + Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils.exportComponentInterface(component); + ToscaRepresentation componentInterfaceYaml = componentInterface.left().value(); + String mainYaml = componentInterfaceYaml.getMainYaml(); + String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName); + + zip.putNextEntry(new ZipEntry(interfaceFileName)); + zip.write(mainYaml.getBytes()); + + } catch (Exception e) { + log.error("#writeComponentInterface - zip writing failed with error: ", e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + return Either.left(zip); + } + + private Either<List<ArtifactDefinition>, ResponseFormat> handleAAIArtifacts(Component component, boolean mockGenerator, List<ImmutablePair<Component, byte[]>> generatorInputs) { + + ComponentTypeEnum componentType = component.getComponentType(); + List<Artifact> generatedArtifacts; + List<ArtifactDefinition> aaiArtifacts = new LinkedList<>(); + + if (componentType == ComponentTypeEnum.SERVICE && !generatorInputs.isEmpty()) { + List<Artifact> convertedGeneratorInputs = convertToGeneratorArtifactsInput(generatorInputs); + + Either<List<Artifact>, String> generatorResponse; + + if (mockGenerator) { + generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.OTHER, component); + } else { + generatorResponse = artifactGenerator(convertedGeneratorInputs, ArtifactType.AAI, component); + } + + if (generatorResponse.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), generatorResponse.right().value()); + return Either.right(responseFormat); + } + + generatedArtifacts = generatorResponse.left().value(); + + aaiArtifacts = convertToArtifactDefinitionFromArtifactGeneratedData(generatedArtifacts); + + } + + return Either.left(aaiArtifacts); + } + + private Either<ActionStatus, ResponseFormat> handleAllAAIArtifactsInDataModel(Component component, List<ArtifactDefinition> artifactsFromAAI, boolean shouldLock, boolean inTransaction) { + + Either<ActionStatus, ResponseFormat> handleAAIArtifactsResponse; + User lastComponentUpdater; + + List<ArtifactDefinition> aaiArtifatcsToCreate = getAAIArtifatcsForCreate(artifactsFromAAI, component); + List<ArtifactDefinition> aaiArtifatcsToDelete = getAAIArtifatcsForDelete(artifactsFromAAI, component); + List<ArtifactDefinition> aaiArtifatcsToUpdate = getAAIArtifatcsForUpdate(artifactsFromAAI, component); + + String lastUpdaterUserId = component.getLastUpdaterUserId(); + Either<User, ResponseFormat> validateUserExists = artifactsBusinessLogic.validateUserExists(lastUpdaterUserId, "CSAR creation util", true); + + if (validateUserExists.isRight()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, component.getComponentType().getValue(), component.getName(), "User not found"); + return Either.right(responseFormat); + } + + lastComponentUpdater = validateUserExists.left().value(); + + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToDelete, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DELETE), lastComponentUpdater, shouldLock, + inTransaction); + + if (handleAAIArtifactsResponse.isRight()) { + return handleAAIArtifactsResponse; + } + + handleAAIArtifactsResponse = handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToCreate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.CREATE), lastComponentUpdater, shouldLock, + inTransaction); + + if (handleAAIArtifactsResponse.isRight()) { + return handleAAIArtifactsResponse; + } + + return handleAAIArtifactsInDataModelByOperationType(component, aaiArtifatcsToUpdate, artifactsBusinessLogic.new ArtifactOperationInfo(false, false, ArtifactOperationEnum.UPDATE), lastComponentUpdater, shouldLock, inTransaction); + } + + private List<ArtifactDefinition> getAAIArtifatcsForUpdate(List<ArtifactDefinition> artifactsFromAAI, Component component) { + + Set<String> componetDeploymentArtifactLables = component.getDeploymentArtifacts().keySet(); + Set<String> componetInformationalArtifactLables = component.getArtifacts().keySet(); + + return artifactsFromAAI.stream() + .filter(e -> componetDeploymentArtifactLables.contains(e.getArtifactLabel()) || componetInformationalArtifactLables.contains(e.getArtifactLabel())) + .filter(e -> checkAaiForUpdate(component, e)) + .collect(Collectors.toList()); + } + + private boolean checkAaiForUpdate(Component component, ArtifactDefinition artifactDefinition) { + ArtifactDefinition artifactDefinitionComp = component.getDeploymentArtifacts().get(artifactDefinition.getArtifactLabel()); + + if (artifactDefinitionComp == null) { + log.warn("Failed to get {} artifact", artifactDefinition.getArtifactLabel()); + return false; + } + + // Old Artifacts before the generated flag introduction if contains "aai" ignore case prefix updated + if (artifactDefinitionComp.getGenerated() == null) { + if (artifactDefinitionComp.getArtifactLabel().toLowerCase().startsWith("aai")) { + return true; + } else { + log.warn("The artifact {} flag is null but AAI prefix is abssent Not updated", artifactDefinition.getArtifactLabel()); + } + } else { + if (artifactDefinition.getGenerated()) { + return true; + } else { + log.warn("Generated artifact {} was already uploaded manually", artifactDefinition.getArtifactLabel()); + } + } + return false; + } + + private List<ArtifactDefinition> getAAIArtifatcsForDelete(List<ArtifactDefinition> artifactsFromAAI, Component component) { + + Set<String> aaiLabels = artifactsFromAAI.stream() + .map(ArtifactDefinition::getArtifactLabel) + .collect(Collectors.toSet()); + + List<ArtifactDefinition> artifactsForDeleteDeployment = component.getDeploymentArtifacts().values().stream() + // Filter Out Artifacts that are not contained in artifacts returned + // from AAI API + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); + + List<ArtifactDefinition> artifactsForDeleteInformational = component.getArtifacts().values().stream() + // Filter Out Artifacts that are not contained in artifacts returned + // from AAI API + .filter(e -> !aaiLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); + + artifactsForDeleteDeployment.addAll(artifactsForDeleteInformational); + + return artifactsForDeleteDeployment.stream() + .filter(e -> (e.getGenerated() != null && e.getGenerated().equals(Boolean.TRUE)) || (e.getGenerated() == null && e.getArtifactLabel().toLowerCase().startsWith("aai"))) + .collect(Collectors.toList()); + } + + private List<ArtifactDefinition> getAAIArtifatcsForCreate(List<ArtifactDefinition> artifactsFromAAI, Component component) { + + Set<String> componentDeploymentLabels = component.getDeploymentArtifacts().keySet(); + Set<String> componentInfoLabels = component.getArtifacts().keySet(); + + // If the artifact label does not exist in the service - + // store the artifact (generate uuid and version, "generated" flag is TRUE) + return artifactsFromAAI.stream() + .filter(e -> !componentDeploymentLabels.contains(e.getArtifactLabel()) && !componentInfoLabels.contains(e.getArtifactLabel())) + .collect(Collectors.toList()); + } + + private Either<ActionStatus, ResponseFormat> handleAAIArtifactsInDataModelByOperationType(Component component, List<ArtifactDefinition> generatedArtifactsDefinitions, ArtifactOperationInfo operationType, User user, boolean shouldLock, + boolean inTransaction) { + + String componentUniqueId = component.getUniqueId(); + ComponentTypeEnum componentType = component.getComponentType(); + + for (ArtifactDefinition artDef : generatedArtifactsDefinitions) { + String data = gson.toJson(artDef); + String dataMD5 = GeneralUtility.calculateMD5Base64EncodedByString(data); + String artifactUniqueId = null; + + if ((operationType.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) || (operationType.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE)) { + String artifactLabel = artDef.getArtifactLabel(); + ArtifactDefinition artifactDefinition = component.getDeploymentArtifacts().get(artifactLabel); + if (artifactDefinition != null) { + artifactUniqueId = artifactDefinition.getUniqueId(); + } + } + + Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact = artifactsBusinessLogic.validateAndHandleArtifact(componentUniqueId, componentType, operationType, artifactUniqueId, artDef, dataMD5, data, null, + null, user, component, shouldLock, inTransaction, false); + + if (validateAndHandleArtifact.isRight()) { + if (ArtifactOperationEnum.isCreateOrLink(operationType.getArtifactOperationEnum()) || ArtifactOperationEnum.UPDATE == operationType.getArtifactOperationEnum()) { + ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.AAI_ARTIFACT_GENERATION_FAILED, componentType.getValue(), component.getName(), validateAndHandleArtifact.right().value().toString()); + + Either.right(responseFormat); + } else { + log.warn("Generated artifact {} could not be deleted", artDef.getArtifactLabel()); + } + } + } + + return Either.left(ActionStatus.OK); + } + + private List<ArtifactDefinition> convertToArtifactDefinitionFromArtifactGeneratedData(List<Artifact> generatorOutput) { + List<ArtifactDefinition> artifactDefList = new LinkedList<>(); + + for (Artifact artifact : generatorOutput) { + ArtifactDefinition newEntry = new ArtifactDefinition(); + newEntry.setArtifactName(artifact.getName()); + newEntry.setArtifactType(artifact.getType()); + newEntry.setArtifactGroupType(ArtifactGroupTypeEnum.findType(artifact.getGroupType())); + newEntry.setDescription(artifact.getDescription()); + + // Normalizing the artifact label to match those stored in DB + String normalizeArtifactLabel = ValidationUtils.normalizeArtifactLabel(artifact.getLabel()); + newEntry.setArtifactLabel(normalizeArtifactLabel); + newEntry.setPayload(Base64.decodeBase64(artifact.getPayload())); + newEntry.setArtifactChecksum(artifact.getChecksum()); + // Flag that set to true in case that the artifact is generated by AI&I generator + newEntry.setGenerated(Boolean.TRUE); + + artifactDefList.add(newEntry); + } + + return artifactDefList; + } + + // List<ImmutablePair<Component, byte[] artifactBytes>> + // artifact stored by label + private List<Artifact> convertToGeneratorArtifactsInput(List<ImmutablePair<Component, byte[]>> inputs) { + List<Artifact> listOfArtifactsInput = new LinkedList<>(); + for (ImmutablePair<Component, byte[]> triple : inputs) { + Component component = triple.getLeft(); + + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + + String artifactName = artifactDefinition.getArtifactName(); + String artifactType = artifactDefinition.getArtifactType(); + String artifactGroupType = artifactDefinition.getArtifactGroupType().getType(); + String artifactDescription = artifactDefinition.getDescription(); + String artifactLabel = artifactDefinition.getArtifactLabel(); + byte[] right = triple.getRight(); + // The md5 calculated on the uncoded data + String md5Hex = DigestUtils.md5Hex(right); + byte[] payload = Base64.encodeBase64(right); + String artifactVersion = artifactDefinition.getArtifactVersion(); + + Artifact convertedArtifact = new Artifact(artifactType, artifactGroupType, md5Hex, payload); + convertedArtifact.setName(artifactName); + convertedArtifact.setDescription(artifactDescription); + convertedArtifact.setLabel(artifactLabel); + convertedArtifact.setVersion(artifactVersion); + + listOfArtifactsInput.add(convertedArtifact); + } + + return listOfArtifactsInput; + } + + private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) { + byte[] content; + if (cassandraId == null || cassandraId.isEmpty()) { + Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent); + if (exportRes.isRight()) { + log.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), exportRes.right().value()); + return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value())); + } + content = exportRes.left().value().getMainYaml().getBytes(); + } else { + Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId); + if (fromCassandra.isRight()) { + return Either.right(fromCassandra.right().value()); + } else { + content = fromCassandra.left().value(); + } + } + return Either.left(content); + } + + private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() { + Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(versionFirstThreeOctates, CONFORMANCE_LEVEL); + + if(specificSchemaFiles.isRight()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse)); + } + + List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value(); + + if(listOfSchemas.isEmpty()){ + log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", versionFirstThreeOctates, CONFORMANCE_LEVEL); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, versionFirstThreeOctates, CONFORMANCE_LEVEL)); + } + + SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next(); + + return Either.left(schemaFile.getPayloadAsArray()); + } + + private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) { + Either<ESArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId); + + if (artifactResponse.isRight()) { + log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value()); + + StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value()); + ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus); + return Either.right(convertedFromStorageResponse); + } + ESArtifactData artifactData = artifactResponse.left().value(); + return Either.left(artifactData.getDataAsArray()); + } + + private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) { + final String BLOCK_0_TEMPLATE = + "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n"; + String readyBlock = String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel); + return readyBlock; + } + + private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) { + final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n"; + return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef); + } + + private Either<List<Artifact>, String> artifactGenerator(List<Artifact> artifactList, ArtifactType type, Component component) { + + ArtifactGenerationServiceImpl artifactGenerationServiceImpl = new ArtifactGenerationServiceImpl(); + ArtifactTypes artifactTypes = new ArtifactTypes(); + List<ArtifactType> artifactTypesList = new LinkedList<>(); + ArtifactType otherType; + + if (type == null) { + otherType = ArtifactType.OTHER; + } else { + otherType = type; + } + + artifactTypesList.add(otherType); + artifactTypes.setArtifactTypes(artifactTypesList); + + String configJson = gson.toJson(artifactTypes); + Map<String, String> additionalParams = new HashMap<>(); + String version; + + if (UUID_NORMATIVE_NEW_VERSION.matcher(component.getVersion()).matches() ) { + version = component.getVersion(); + } else { + String[] versionParts = component.getVersion().split(ToscaElementLifecycleOperation.VERSION_DELIMETER_REGEXP); + Integer majorVersion = Integer.parseInt(versionParts[0]); + + version = (majorVersion + 1) + ToscaElementLifecycleOperation.VERSION_DELIMETER + "0"; + } + + additionalParams.put(AdditionalParams.ServiceVersion.getName(), version); + GenerationData generatedArtifacts = artifactGenerationServiceImpl.generateArtifact(artifactList, configJson, additionalParams); + + Map<String, List<String>> errorData = generatedArtifacts.getErrorData(); + + if (!errorData.isEmpty()) { + Set<String> keySet = errorData.keySet(); + StringBuilder error = new StringBuilder(); + + for (String key : keySet) { + List<String> errorList = errorData.get(key); + log.debug("The Artifact Generator Failed - {} with following: {}", key, errorList); + error.append(key + errorList); + } + + return Either.right(error.toString()); + } + + return Either.left(generatedArtifacts.getResultData()); + } + + /** + * Extracts artifacts of VFCs from CSAR + * + * @param csar + * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace + */ + public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) { + + Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>(); + if (csar != null) { + log.debug("************* Going to extract VFCs artifacts from Csar. "); + Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>(); + csar.entrySet().stream() + // filter CSAR entry by node type artifact path + .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches()) + // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path + .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts)); + // add counter suffix to artifact labels + handleWarningMessages(collectedWarningMessages); + + } + return artifacts; + } + + /** + * Print warnings to log + * + * @param collectedWarningMessages + */ + public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) { + collectedWarningMessages.entrySet().stream() + // for each vfc + .forEach(e -> e.getValue().stream() + // add each warning message to log + .forEach(args -> log.warn(e.getKey(), args.toArray()))); + + } + + private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) { + if (extractedVfcArtifact != null) { + List<ArtifactDefinition> currArtifactsList; + String vfcToscaNamespace = extractedVfcArtifact.getKey(); + if (artifacts.containsKey(vfcToscaNamespace)) { + currArtifactsList = artifacts.get(vfcToscaNamespace); + } else { + currArtifactsList = new ArrayList<>(); + artifacts.put(vfcToscaNamespace, currArtifactsList); + } + currArtifactsList.add(extractedVfcArtifact.getValue()); + } + } + + private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) { + ArtifactDefinition artifact; + String[] parsedCsarArtifactPath = entry.getKey().split("/"); + Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages); + if (eitherArtifactGroupType.isLeft()) { + artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value()); + } else { + return null; + } + return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact); + } + + private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) { + Either<ArtifactGroupTypeEnum, Boolean> result; + try { + ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase()); + if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) { + String warningMessage = "Warning - unrecognized artifact group type {} was received."; + List<String> messageArguments = new ArrayList<>(); + messageArguments.add(groupType); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set<List<String>> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + + result = Either.right(false); + } else { + + result = Either.left(artifactGroupType); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + result = Either.right(false); + } + return result; + } + + private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) { + ArtifactDefinition artifact; + artifact = new ArtifactDefinition(); + artifact.setArtifactGroupType(artifactGroupType); + artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages)); + artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1])); + artifact.setPayloadData(Base64.encodeBase64String(entry.getValue())); + artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName()); + artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName())); + artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR); + artifact.setIsFromCsar(true); + artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue())); + return artifact; + } + + public static final class NonMetaArtifactInfo { + private final String path; + private final String artifactName; + private final String displayName; + private final String artifactLabel; + private final ArtifactTypeEnum artifactType; + private final ArtifactGroupTypeEnum artifactGroupType; + private String payloadData; + private String artifactChecksum; + private String artifactUniqueId; + private final boolean isFromCsar; + + public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, boolean isFromCsar) { + super(); + this.path = path; + this.isFromCsar = isFromCsar; + this.artifactName = ValidationUtils.normalizeFileName(artifactName); + this.artifactType = artifactType; + this.artifactGroupType = artifactGroupType; + final int pointIndex = artifactName.lastIndexOf('.'); + if (pointIndex > 0) { + displayName = artifactName.substring(0, pointIndex); + } else { + displayName = artifactName; + } + this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName); + if (payloadData != null) { + this.payloadData = Base64.encodeBase64String(payloadData); + this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData); + } + this.artifactUniqueId = artifactUniqueId; + } + + public String getPath() { + return path; + } + + public String getArtifactName() { + return artifactName; + } + + public ArtifactTypeEnum getArtifactType() { + return artifactType; + } + + public String getDisplayName() { + return displayName; + } + + public ArtifactGroupTypeEnum getArtifactGroupType() { + return artifactGroupType; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public boolean isFromCsar(){ + return isFromCsar; + } + + public String getPayloadData() { + return payloadData; + } + + public String getArtifactChecksum() { + return artifactChecksum; + } + + public String getArtifactUniqueId() { + return artifactUniqueId; + } + + public void setArtifactUniqueId(String artifactUniqueId) { + this.artifactUniqueId = artifactUniqueId; + } + + } + + /** + * This method checks the artifact GroupType & Artifact Type. <br> + * if there is any problem warning messages are added to collectedWarningMessages + * + * @param artifactPath + * @param collectedWarningMessages + * @return + */ + public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) { + Either<NonMetaArtifactInfo, Boolean> ret; + try { + String[] parsedArtifactPath = artifactPath.split("/"); + // Validate Artifact Group Type + Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages); + if (eitherGroupType.isLeft()) { + final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value(); + + // Validate Artifact Type + String artifactType = parsedArtifactPath[2]; + artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages); + + String artifactFileNameType = parsedArtifactPath[3]; + ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true)); + + } else { + ret = Either.right(eitherGroupType.right().value()); + } + } catch (Exception e) { + log.debug("detectArtifactGroupType failed with exception", e); + ret = Either.right(false); + } + return ret; + + } + + private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName); + } + + private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) { + String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized."; + return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages); + } + + private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) { + + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName); + Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null; + + if(artifactGroupType != null){ + switch (artifactGroupType) { + case INFORMATIONAL: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceInformationalArtifacts(); + break; + case DEPLOYMENT: + resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration() + .getResourceDeploymentArtifacts(); + break; + default: + break; + } + } + + Set<String> validArtifactTypes = null; + if(resourceValidTypeArtifacts != null){ + validArtifactTypes = resourceValidTypeArtifacts.keySet(); + } + + if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) { + List<String> messageArguments = new ArrayList<>(); + messageArguments.add(receivedTypeName); + messageArguments.addAll(Arrays.asList(arguments)); + if (!collectedWarningMessages.containsKey(warningMessage)) { + Set<List<String>> messageArgumentLists = new HashSet<>(); + messageArgumentLists.add(messageArguments); + collectedWarningMessages.put(warningMessage, messageArgumentLists); + } else { + collectedWarningMessages.get(warningMessage).add(messageArguments); + } + } + + return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType(); + } + + private Either<ZipOutputStream, ResponseFormat> writeAllFilesToScar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{ + ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts(); + + Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath = writeComponentArtifactsToSpecifiedtPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + + ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + + Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts(); + Set<String> keySet = componentInstancesArtifacts.keySet(); + + String currentPath = ARTIFACTS_PATH + RESOURCES_PATH; + for (String keyAssetName : keySet) { + ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName); + String pathWithAssetName = currentPath + keyAssetName + "/"; + writeComponentArtifactsToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest); + + if(writeComponentArtifactsToSpecifiedtPath.isRight()){ + return Either.right(writeComponentArtifactsToSpecifiedtPath.right().value()); + } + } + + return Either.left(zipstream); + } + + private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedtPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream, + String currentPath, boolean isInCertificationRequest) throws IOException { + Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); + //Keys are defined: + //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>. + //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0" + Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet(); + for (String keyAssetName : componentTypeArtifactsKeys) { + ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName); + ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts(); + String pathWithAssetName = currentPath + keyAssetName + "/"; + Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest); + + if(writeArtifactsInfoToSpecifiedtPath.isRight()){ + return writeArtifactsInfoToSpecifiedtPath; + } + } + + return Either.left(zipstream); + } + + private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException { + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo + .getArtifactsInfo(); + Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet(); + + for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) { + String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + "/"; + + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum); + Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet(); + + for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) { + List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum); + String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + "/"; + + Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest); + + if(writeArtifactDefinition.isRight()){ + return writeArtifactDefinition; + } + } + } + + return Either.left(zip); + } + + private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList, + String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException { + + ComponentTypeEnum componentType = mainComponent.getComponentType(); + String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType(); + + for (ArtifactDefinition artifactDefinition : artifactDefinitionList) { + if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE + && artifactDefinition.getArtifactType().equals(heatEnvType) || //this is placeholder (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){ - continue; - } - - byte[] payloadData = artifactDefinition.getPayloadData(); - String artifactFileName = artifactDefinition.getArtifactName(); - - if (payloadData == null) { - Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId()); - - if (fromCassandra.isRight()) { + continue; + } + + byte[] payloadData = artifactDefinition.getPayloadData(); + String artifactFileName = artifactDefinition.getArtifactName(); + + if (payloadData == null) { + Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId()); + + if (fromCassandra.isRight()) { log.debug("ArtifactName {}, unique ID {}", artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId()); - log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value()); - continue; - } - payloadData = fromCassandra.left().value(); - } - zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName)); - zip.write(payloadData); - } - - return Either.left(zip); - } - - /************************************ Artifacts Structure ******************************************************************/ - /** - * The artifacts Definition saved by their structure - */ - private class ArtifactsInfo { - //Key is the type of artifacts(Informational/Deployment) - //Value is a map between an artifact type and a list of all artifacts of this type - private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField; - - public ArtifactsInfo() { - this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class); - } - - public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() { - return artifactsInfoField; - } - - public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){ - List<ArtifactDefinition> artifacts = new ArrayList<>(); - for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){ - artifacts.addAll(artifactsByType); - } - return artifacts; - } - - public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){ - artifactsInfoField.put(artifactGroup, artifactsDefinition); - } - - public boolean isEmpty() { - return artifactsInfoField.isEmpty(); - } - - } - - /** - * The artifacts of the component and of all its composed instances - * - */ - private class ComponentTypeArtifacts { - private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders) - private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder) - - public ComponentTypeArtifacts() { - componentArtifacts = new ArtifactsInfo(); - componentInstancesArtifacts = new HashMap<>(); - } - - public ArtifactsInfo getComponentArtifacts() { - return componentArtifacts; - } - public void setComponentArtifacts(ArtifactsInfo artifactsInfo) { - this.componentArtifacts = artifactsInfo; - } - public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() { - return componentInstancesArtifacts; - } - public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) { - this.componentInstancesArtifacts = componentInstancesArtifacts; - } - - public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) { - componentInstancesArtifacts.put(normalizedName, artifactsInfo); - } - - } - - private class ComponentArtifacts { - //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component) - private ComponentTypeArtifacts mainTypeAndCIArtifacts; - //artifacts of all component types mapped by their tosca name - private Map<String, ComponentTypeArtifacts> componentTypeArtifacts; - - public ComponentArtifacts(){ - mainTypeAndCIArtifacts = new ComponentTypeArtifacts(); - componentTypeArtifacts = new HashMap<>(); - } - - public ComponentTypeArtifacts getMainTypeAndCIArtifacts() { - return mainTypeAndCIArtifacts; - } - - public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { - this.mainTypeAndCIArtifacts = componentInstanceArtifacts; - } - - public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() { - return componentTypeArtifacts; - } - - public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) { - this.componentTypeArtifacts = componentTypeArtifacts; - } - } - - private class CsarDefinition { - private ComponentArtifacts componentArtifacts; - - // add list of tosca artifacts and meta describes CSAR zip root - - public CsarDefinition(ComponentArtifacts componentArtifacts) { - this.componentArtifacts = componentArtifacts; - } - - public ComponentArtifacts getComponentArtifacts() { - return componentArtifacts; - } - } - - /************************************ Artifacts Structure END******************************************************************/ - - private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){ - ComponentArtifacts componentArtifacts = new ComponentArtifacts(); - Component updatedComponent = component; - - //get service to receive the AII artifacts uploaded to the service - if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { - Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId()); - - if(getServiceResponse.isRight()){ - ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value()); - return Either.right(componentsUtils.getResponseFormat(actionStatus)); - } - - updatedComponent = getServiceResponse.left().value(); - } - - //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder - ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts(); - ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent); - componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); - componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); - - Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version) - //get the component instances - List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances(); - if (componentInstances!=null){ - for (ComponentInstance componentInstance:componentInstances){ - //call recursive to find artifacts for all the path - Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( - updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); - if (collectComponentInstanceArtifacts.isRight()){ - return Either.right(collectComponentInstanceArtifacts.right().value()); - } - } - } - - if(log.isDebugEnabled()){ - printResult(componentArtifacts,updatedComponent.getName()); - } - - return Either.left(new CsarDefinition(componentArtifacts)); - } - - private void printResult(ComponentArtifacts componentArtifacts, String name) { - StringBuilder result = new StringBuilder(); - result.append("Artifacts of main component " + name + "\n"); - ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); - printArtifacts(componentInstanceArtifacts); - result.append("Type Artifacts\n"); - for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){ - result.append("Folder " + typeArtifacts.getKey() + "\n"); - result.append(printArtifacts(typeArtifacts.getValue())); - } - - if(log.isDebugEnabled()){ - log.debug(result.toString()); - } - } - - private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { - StringBuilder result = new StringBuilder(); - ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); - Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo(); - printArtifacts(componetArtifacts); - result = result.append("Resources\n"); - for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){ - result.append("Folder" + resourceInstance.getKey() + "\n"); - result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); - } - - return result.toString(); - } - - private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) { - StringBuilder result = new StringBuilder(); - for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){ - result.append(" " + artifactGroup.getKey().getType()); - for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){ - result.append(" " + groupArtifacts.getKey().getType()); - for (ArtifactDefinition artifact:groupArtifacts.getValue()){ - result.append(" " + artifact.getArtifactDisplayName()); - } - } - } - - return result.toString(); - } - - private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance, - Resource fetchedComponent) { - String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(); - - ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName); - //if there are no artifacts for this component type we need to fetch and build them - if (componentArtifactsInfo==null){ - ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent); - componentArtifactsInfo = new ComponentTypeArtifacts(); - if (!componentArtifacts.isEmpty()){ - componentArtifactsInfo.setComponentArtifacts(componentArtifacts); - resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo); - } - } - return componentArtifactsInfo; - } - - private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance, - Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) { - //1. get the component instance component - String componentUid = componentInstance.getComponentUid(); - Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid); - if (resource.isRight()) { - log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID()); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION, - parentComponent.getComponentType().getValue(), parentComponent.getUUID(), - componentInstance.getOriginType().getComponentType().getValue(), componentUid)); - } - Resource fetchedComponent = resource.left().value(); - - //2. fill the artifacts for the current component parent type - ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent); - - //3. find the artifacts specific to the instance - Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); - Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts = - getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), - componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); - - //4. add the instances artifacts to the component type - ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts); - } - if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts); - } - if (!artifactsInfo.isEmpty()){ - instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo); - } - - //5. do the same for all the component instances - List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances(); - if (componentInstances!=null){ - for (ComponentInstance childComponentInstance:componentInstances){ - Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( - fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); - if (collectComponentInstanceArtifacts.isRight()){ - return collectComponentInstanceArtifacts; - } - } - } - - return Either.left(true); - } - - private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts, - Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) { - Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance - - Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class); - if (componentArtifacts!=null){ - for (ArtifactDefinition artifact:componentArtifacts.values()){ - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); - List<ArtifactDefinition> parentArtifactsByType = null; - if (parentArtifacts!=null){ - parentArtifactsByType = parentArtifacts.get(artifactType); - } - //the artifact is of instance - if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){ - List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType); - if (typeArtifacts == null){ - typeArtifacts = new ArrayList<>(); - artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts); - } - typeArtifacts.add(artifact); - } - } - } - - return artifactsByTypeOfComponentInstance; - } - - private ArtifactsInfo collectComponentArtifacts(Component component) { - Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts(); - Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts); - Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); - Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts); - ArtifactsInfo artifactsInfo = new ArtifactsInfo(); - if (!informationalArtifactsByType.isEmpty()){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); - } - if (!deploymentArtifactsByType.isEmpty() ){ - artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); - } - - return artifactsInfo; - } - - private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) { - Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class); - for (ArtifactDefinition artifact:componentArtifacts.values()){ - if (artifact.getArtifactUUID()!=null){ - ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); - List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType); - if (typeArtifacts==null){ - typeArtifacts = new ArrayList<>(); - artifactsByType.put(artifactType, typeArtifacts); - } - typeArtifacts.add(artifact); - } - } - return artifactsByType; - } + log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value()); + continue; + } + payloadData = fromCassandra.left().value(); + } + zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName)); + zip.write(payloadData); + } + + return Either.left(zip); + } + + /************************************ Artifacts Structure ******************************************************************/ + /** + * The artifacts Definition saved by their structure + */ + private class ArtifactsInfo { + //Key is the type of artifacts(Informational/Deployment) + //Value is a map between an artifact type and a list of all artifacts of this type + private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField; + + public ArtifactsInfo() { + this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class); + } + + public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() { + return artifactsInfoField; + } + + public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){ + List<ArtifactDefinition> artifacts = new ArrayList<>(); + for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){ + artifacts.addAll(artifactsByType); + } + return artifacts; + } + + public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){ + artifactsInfoField.put(artifactGroup, artifactsDefinition); + } + + public boolean isEmpty() { + return artifactsInfoField.isEmpty(); + } + + } + + /** + * The artifacts of the component and of all its composed instances + * + */ + private class ComponentTypeArtifacts { + private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders) + private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder) + + public ComponentTypeArtifacts() { + componentArtifacts = new ArtifactsInfo(); + componentInstancesArtifacts = new HashMap<>(); + } + + public ArtifactsInfo getComponentArtifacts() { + return componentArtifacts; + } + public void setComponentArtifacts(ArtifactsInfo artifactsInfo) { + this.componentArtifacts = artifactsInfo; + } + public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() { + return componentInstancesArtifacts; + } + public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) { + this.componentInstancesArtifacts = componentInstancesArtifacts; + } + + public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) { + componentInstancesArtifacts.put(normalizedName, artifactsInfo); + } + + } + + private class ComponentArtifacts { + //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component) + private ComponentTypeArtifacts mainTypeAndCIArtifacts; + //artifacts of all component types mapped by their tosca name + private Map<String, ComponentTypeArtifacts> componentTypeArtifacts; + + public ComponentArtifacts(){ + mainTypeAndCIArtifacts = new ComponentTypeArtifacts(); + componentTypeArtifacts = new HashMap<>(); + } + + public ComponentTypeArtifacts getMainTypeAndCIArtifacts() { + return mainTypeAndCIArtifacts; + } + + public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + this.mainTypeAndCIArtifacts = componentInstanceArtifacts; + } + + public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() { + return componentTypeArtifacts; + } + + public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) { + this.componentTypeArtifacts = componentTypeArtifacts; + } + } + + private class CsarDefinition { + private ComponentArtifacts componentArtifacts; + + // add list of tosca artifacts and meta describes CSAR zip root + + public CsarDefinition(ComponentArtifacts componentArtifacts) { + this.componentArtifacts = componentArtifacts; + } + + public ComponentArtifacts getComponentArtifacts() { + return componentArtifacts; + } + } + + /************************************ Artifacts Structure END******************************************************************/ + + private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){ + ComponentArtifacts componentArtifacts = new ComponentArtifacts(); + Component updatedComponent = component; + + //get service to receive the AII artifacts uploaded to the service + if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) { + Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId()); + + if(getServiceResponse.isRight()){ + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value()); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + + updatedComponent = getServiceResponse.left().value(); + } + + //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder + ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts(); + ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent); + componentInstanceArtifacts.setComponentArtifacts(artifactsInfo); + componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts); + + Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version) + //get the component instances + List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances(); + if (componentInstances!=null){ + for (ComponentInstance componentInstance:componentInstances){ + //call recursive to find artifacts for all the path + Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts); + if (collectComponentInstanceArtifacts.isRight()){ + return Either.right(collectComponentInstanceArtifacts.right().value()); + } + } + } + + if(log.isDebugEnabled()){ + printResult(componentArtifacts,updatedComponent.getName()); + } + + return Either.left(new CsarDefinition(componentArtifacts)); + } + + private void printResult(ComponentArtifacts componentArtifacts, String name) { + StringBuilder result = new StringBuilder(); + result.append("Artifacts of main component " + name + "\n"); + ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts(); + printArtifacts(componentInstanceArtifacts); + result.append("Type Artifacts\n"); + for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){ + result.append("Folder " + typeArtifacts.getKey() + "\n"); + result.append(printArtifacts(typeArtifacts.getValue())); + } + + if(log.isDebugEnabled()){ + log.debug(result.toString()); + } + } + + private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) { + StringBuilder result = new StringBuilder(); + ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts(); + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo(); + printArtifacts(componetArtifacts); + result = result.append("Resources\n"); + for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){ + result.append("Folder" + resourceInstance.getKey() + "\n"); + result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo())); + } + + return result.toString(); + } + + private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) { + StringBuilder result = new StringBuilder(); + for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){ + result.append(" " + artifactGroup.getKey().getType()); + for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){ + result.append(" " + groupArtifacts.getKey().getType()); + for (ArtifactDefinition artifact:groupArtifacts.getValue()){ + result.append(" " + artifact.getArtifactDisplayName()); + } + } + } + + return result.toString(); + } + + private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance, + Resource fetchedComponent) { + String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion(); + + ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName); + //if there are no artifacts for this component type we need to fetch and build them + if (componentArtifactsInfo==null){ + ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent); + componentArtifactsInfo = new ComponentTypeArtifacts(); + if (!componentArtifacts.isEmpty()){ + componentArtifactsInfo.setComponentArtifacts(componentArtifacts); + resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo); + } + } + return componentArtifactsInfo; + } + + private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance, + Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) { + //1. get the component instance component + String componentUid = componentInstance.getComponentUid(); + Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(componentUid); + if (resource.isRight()) { + log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID()); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION, + parentComponent.getComponentType().getValue(), parentComponent.getUUID(), + componentInstance.getOriginType().getComponentType().getValue(), componentUid)); + } + Resource fetchedComponent = resource.left().value(); + + //2. fill the artifacts for the current component parent type + ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent); + + //3. find the artifacts specific to the instance + Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts = + getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL); + Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts = + getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(), + componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT); + + //4. add the instances artifacts to the component type + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts); + } + if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts); + } + if (!artifactsInfo.isEmpty()){ + instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo); + } + + //5. do the same for all the component instances + List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances(); + if (componentInstances!=null){ + for (ComponentInstance childComponentInstance:componentInstances){ + Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts( + fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts); + if (collectComponentInstanceArtifacts.isRight()){ + return collectComponentInstanceArtifacts; + } + } + } + + return Either.left(true); + } + + private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts, + Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) { + Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance + + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class); + if (componentArtifacts!=null){ + for (ArtifactDefinition artifact:componentArtifacts.values()){ + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List<ArtifactDefinition> parentArtifactsByType = null; + if (parentArtifacts!=null){ + parentArtifactsByType = parentArtifacts.get(artifactType); + } + //the artifact is of instance + if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){ + List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType); + if (typeArtifacts == null){ + typeArtifacts = new ArrayList<>(); + artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + } + + return artifactsByTypeOfComponentInstance; + } + + private ArtifactsInfo collectComponentArtifacts(Component component) { + Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts(); + Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts); + Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts(); + Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts); + ArtifactsInfo artifactsInfo = new ArtifactsInfo(); + if (!informationalArtifactsByType.isEmpty()){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType); + } + if (!deploymentArtifactsByType.isEmpty() ){ + artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType); + } + + return artifactsInfo; + } + + private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) { + Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class); + for (ArtifactDefinition artifact:componentArtifacts.values()){ + if (artifact.getArtifactUUID()!=null){ + ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType()); + List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType); + if (typeArtifacts==null){ + typeArtifacts = new ArrayList<>(); + artifactsByType.put(artifactType, typeArtifacts); + } + typeArtifacts.add(artifact); + } + } + return artifactsByType; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java index 083ea67769..f40ebf0e64 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/PropertyConvertor.java @@ -49,59 +49,59 @@ import com.google.gson.stream.JsonReader; import fj.data.Either; public class PropertyConvertor { - private static PropertyConvertor instance; - private JsonParser jsonParser = new JsonParser(); - private static Logger log = LoggerFactory.getLogger(PropertyConvertor.class.getName()); - Gson gson = new Gson(); - protected PropertyConvertor() { - - } - - public static synchronized PropertyConvertor getInstance() { - if (instance == null) { - instance = new PropertyConvertor(); - } - return instance; - } - - public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType, Map<String, DataTypeDefinition> dataTypes) { - - if (component instanceof Resource) { - Resource resource = (Resource) component; - List<PropertyDefinition> props = resource.getProperties(); - if (props != null) { - Map<String, ToscaProperty> properties = new HashMap<>(); - - // take only the properties of this resource - props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> { + private static PropertyConvertor instance; + private JsonParser jsonParser = new JsonParser(); + private static final Logger log = LoggerFactory.getLogger(PropertyConvertor.class); + Gson gson = new Gson(); + protected PropertyConvertor() { + + } + + public static synchronized PropertyConvertor getInstance() { + if (instance == null) { + instance = new PropertyConvertor(); + } + return instance; + } + + public Either<ToscaNodeType, ToscaError> convertProperties(Component component, ToscaNodeType toscaNodeType, Map<String, DataTypeDefinition> dataTypes) { + + if (component instanceof Resource) { + Resource resource = (Resource) component; + List<PropertyDefinition> props = resource.getProperties(); + if (props != null) { + Map<String, ToscaProperty> properties = new HashMap<>(); + + // take only the properties of this resource + props.stream().filter(p -> p.getOwnerId() == null || p.getOwnerId().equals(component.getUniqueId())).forEach(property -> { properties.put(property.getName(), convertProperty(dataTypes, property, false)); - }); - if (!properties.isEmpty()) { - toscaNodeType.setProperties(properties); - } - } - } - return Either.left(toscaNodeType); - } - - public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, boolean isCapabiltyProperty) { - ToscaProperty prop = new ToscaProperty(); - - String innerType = null; - SchemaDefinition schema = property.getSchema(); - if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) { - innerType = schema.getProperty().getType(); - EntrySchema eschema = new EntrySchema(); - eschema.setType(innerType); - eschema.setDescription(schema.getProperty().getDescription()); - prop.setEntry_schema(eschema); - } - log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue()); + }); + if (!properties.isEmpty()) { + toscaNodeType.setProperties(properties); + } + } + } + return Either.left(toscaNodeType); + } + + public ToscaProperty convertProperty(Map<String, DataTypeDefinition> dataTypes, PropertyDefinition property, boolean isCapabiltyProperty) { + ToscaProperty prop = new ToscaProperty(); + + String innerType = null; + SchemaDefinition schema = property.getSchema(); + if (schema != null && schema.getProperty() != null && schema.getProperty().getType() != null && !schema.getProperty().getType().isEmpty()) { + innerType = schema.getProperty().getType(); + EntrySchema eschema = new EntrySchema(); + eschema.setType(innerType); + eschema.setDescription(schema.getProperty().getDescription()); + prop.setEntry_schema(eschema); + } + log.trace("try to convert property {} from type {} with default value [{}]", property.getName(), property.getType(), property.getDefaultValue()); Object convertedObj = convertToToscaObject(property.getType(), property.getDefaultValue(), innerType, dataTypes); if (convertedObj != null) { prop.setDefaultp(convertedObj); } - prop.setType(property.getType()); + prop.setType(property.getType()); prop.setDescription(property.getDescription()); if (isCapabiltyProperty) { prop.setStatus(property.getStatus()); @@ -109,91 +109,91 @@ public class PropertyConvertor { } return prop; - } - - public Object convertToToscaObject(String propertyType, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { - log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType); - if (StringUtils.isEmpty(value)) { - value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes); - if(StringUtils.isEmpty(value)){ - return null; - } - } - try { - ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance(); - ToscaValueConverter innerConverter = null; - Boolean isScalar = true; - - ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); - if (type == null) { - log.trace("isn't prederfined type, get from all data types"); - DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); - if (innerType == null) { - innerType = propertyType; - } - - if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) { - log.trace("This is scalar type. get suitable converter for type {}", type); - innerConverter = type.getValueConverter(); - } else { - isScalar = false; - } - } else { - ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType()); - if (typeIfScalar == null) { - isScalar = false; - } - - innerConverter = type.getValueConverter(); - if (ToscaPropertyType.STRING.equals(type) && valueStartsWithNonJsonChar(value)) { - return innerConverter.convertToToscaValue(value, innerType, dataTypes); - } - } - JsonElement jsonElement = null; - - StringReader reader = new StringReader(value); - JsonReader jsonReader = new JsonReader(reader); - jsonReader.setLenient(true); - - jsonElement = jsonParser.parse(jsonReader); - - if (value.equals("")) { - return value; - } - - if (jsonElement.isJsonPrimitive() && isScalar) { - log.trace("It's well defined type. convert it"); - ToscaValueConverter converter = type.getValueConverter(); - return converter.convertToToscaValue(value, innerType, dataTypes); - } else { - log.trace("It's data type or inputs in primitive type. convert as map"); - Object convertedValue; - if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) { - convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); - } else { - if (isScalar) { - // complex json for scalar type - convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement); - } else { - if (innerConverter != null) { - convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); - } else { - convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement); - } - } - } - return convertedValue; - } - - } catch (Exception e) { - log.debug("convertToToscaValue failed to parse json value :", e); - return null; - } - - } - - private boolean valueStartsWithNonJsonChar(String value) { - return value.startsWith("/") || value.startsWith(":"); - } + } + + public Object convertToToscaObject(String propertyType, String value, String innerType, Map<String, DataTypeDefinition> dataTypes) { + log.trace("try to convert propertyType {} , value [{}], innerType {}", propertyType, value, innerType); + if (StringUtils.isEmpty(value)) { + value = DataTypePropertyConverter.getInstance().getDataTypePropertiesDefaultValuesRec(propertyType, dataTypes); + if(StringUtils.isEmpty(value)){ + return null; + } + } + try { + ToscaMapValueConverter mapConverterInst = ToscaMapValueConverter.getInstance(); + ToscaValueConverter innerConverter = null; + Boolean isScalar = true; + + ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType); + if (type == null) { + log.trace("isn't prederfined type, get from all data types"); + DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); + if (innerType == null) { + innerType = propertyType; + } + + if ((type = mapConverterInst.isScalarType(dataTypeDefinition)) != null) { + log.trace("This is scalar type. get suitable converter for type {}", type); + innerConverter = type.getValueConverter(); + } else { + isScalar = false; + } + } else { + ToscaPropertyType typeIfScalar = ToscaPropertyType.getTypeIfScalar(type.getType()); + if (typeIfScalar == null) { + isScalar = false; + } + + innerConverter = type.getValueConverter(); + if (ToscaPropertyType.STRING.equals(type) && valueStartsWithNonJsonChar(value)) { + return innerConverter.convertToToscaValue(value, innerType, dataTypes); + } + } + JsonElement jsonElement = null; + + StringReader reader = new StringReader(value); + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + + jsonElement = jsonParser.parse(jsonReader); + + if (value.equals("")) { + return value; + } + + if (jsonElement.isJsonPrimitive() && isScalar) { + log.trace("It's well defined type. convert it"); + ToscaValueConverter converter = type.getValueConverter(); + return converter.convertToToscaValue(value, innerType, dataTypes); + } else { + log.trace("It's data type or inputs in primitive type. convert as map"); + Object convertedValue; + if (innerConverter != null && (ToscaPropertyType.MAP.equals(type) || ToscaPropertyType.LIST.equals(type))) { + convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); + } else { + if (isScalar) { + // complex json for scalar type + convertedValue = mapConverterInst.handleComplexJsonValue(jsonElement); + } else { + if (innerConverter != null) { + convertedValue = innerConverter.convertToToscaValue(value, innerType, dataTypes); + } else { + convertedValue = mapConverterInst.convertDataTypeToToscaObject(innerType, dataTypes, innerConverter, isScalar, jsonElement); + } + } + } + return convertedValue; + } + + } catch (Exception e) { + log.debug("convertToToscaValue failed to parse json value :", e); + return null; + } + + } + + private boolean valueStartsWithNonJsonChar(String value) { + return value.startsWith("/") || value.startsWith(":"); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java index 94dd559d2d..c3acb43186 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaError.java @@ -22,5 +22,5 @@ package org.openecomp.sdc.be.tosca; public enum ToscaError { - NODE_TYPE_CAPABILITY_ERROR, NOT_SUPPORTED_TOSCA_TYPE, NODE_TYPE_REQUIREMENT_ERROR, GENERAL_ERROR + NODE_TYPE_CAPABILITY_ERROR, NOT_SUPPORTED_TOSCA_TYPE, NODE_TYPE_REQUIREMENT_ERROR, GENERAL_ERROR } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index c37c15f694..05be7f9cda 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -20,19 +20,7 @@ package org.openecomp.sdc.be.tosca; -import java.beans.IntrospectionException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; -import java.util.stream.Collectors; - +import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; @@ -44,42 +32,16 @@ import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; -import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.CapabilityDefinition; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.ComponentInstance; -import org.openecomp.sdc.be.model.ComponentInstanceInput; -import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.GroupDefinition; -import org.openecomp.sdc.be.model.GroupInstance; -import org.openecomp.sdc.be.model.GroupProperty; -import org.openecomp.sdc.be.model.InputDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.RelationshipInfo; -import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; -import org.openecomp.sdc.be.model.RequirementDefinition; -import org.openecomp.sdc.be.model.Resource; -import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.tosca.converters.ToscaValueBaseConverter; -import org.openecomp.sdc.be.tosca.model.IToscaMetadata; -import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; -import org.openecomp.sdc.be.tosca.model.ToscaCapability; -import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaMetadata; -import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaNodeType; -import org.openecomp.sdc.be.tosca.model.ToscaProperty; -import org.openecomp.sdc.be.tosca.model.ToscaTemplate; -import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; -import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate; -import org.openecomp.sdc.be.tosca.model.VfModuleToscaMetadata; +import org.openecomp.sdc.be.tosca.model.*; +import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil; import org.openecomp.sdc.common.api.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -97,1119 +59,1158 @@ import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Represent; import org.yaml.snakeyaml.representer.Representer; -import fj.data.Either; +import java.beans.IntrospectionException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; @org.springframework.stereotype.Component("tosca-export-handler") public class ToscaExportHandler { - @Autowired - private ApplicationDataTypeCache dataTypeCache; - - @Autowired - private ToscaOperationFacade toscaOperationFacade; - @Autowired - private CapabiltyRequirementConvertor capabiltyRequirementConvertor; - private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance(); - Map<String, Component> originComponents = new HashMap<>(); - - private static Logger log = LoggerFactory.getLogger(ToscaExportHandler.class.getName()); - - public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1"; - public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service."; - public static final String IMPORTS_FILE_KEY = "file"; - public static final String TOSCA_TEMPLATE_NAME = "-template.yml"; - public static final String TOSCA_INTERFACE_NAME = "-interface.yml"; - public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; - public static final String VF_MODULE_TYPE_KEY = "vf_module_type"; - public static final String VF_MODULE_DESC_KEY = "vf_module_description"; - public static final String VOLUME_GROUP_KEY = "volume_group"; - public static final String VF_MODULE_TYPE_BASE = "Base"; - public static final String VF_MODULE_TYPE_EXPANSION = "Expansion"; - private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration"; - private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; - protected static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager - .getConfigurationManager().getConfiguration().getDefaultImports(); - - public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) { - - Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component); - if (toscaTemplateRes.isRight()) { - return Either.right(toscaTemplateRes.right().value()); - } - - ToscaTemplate toscaTemplate = toscaTemplateRes.left().value(); - ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); - return Either.left(toscaRepresentation); - } - - public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) { - if (null == DEFAULT_IMPORTS) { - log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); - return Either.right(ToscaError.GENERAL_ERROR); - } - - ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); - toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); - Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); - Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, - nodeTypes); - if (toscaTemplateRes.isRight()) { - return Either.right(toscaTemplateRes.right().value()); - } - - toscaTemplate = toscaTemplateRes.left().value(); - ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); - return Either.left(toscaRepresentation); - } - - public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) { - CustomRepresenter representer = new CustomRepresenter(); - DumperOptions options = new DumperOptions(); - options.setAllowReadOnlyProperties(false); - options.setPrettyFlow(true); - - options.setDefaultFlowStyle(FlowStyle.FLOW); - options.setCanonical(false); - - representer.addClassTag(toscaTemplate.getClass(), Tag.MAP); - - representer.setPropertyUtils(new UnsortedPropertyUtils()); - Yaml yaml = new Yaml(representer, options); - - String yamlAsString = yaml.dumpAsMap(toscaTemplate); - - StringBuilder sb = new StringBuilder(); - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); - sb.append(yamlAsString); - sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); - - ToscaRepresentation toscaRepresentation = new ToscaRepresentation(); - toscaRepresentation.setMainYaml(sb.toString()); - toscaRepresentation.setDependencies(toscaTemplate.getDependencies()); - - return toscaRepresentation; - } - - public Either<ToscaTemplate, ToscaError> getDependencies(Component component) { - ToscaTemplate toscaTemplate = new ToscaTemplate(null); - Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component, - toscaTemplate); - if (fillImports.isRight()) { - return Either.right(fillImports.right().value()); - } - return Either.left(fillImports.left().value().left); - } - - private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) { - if (null == DEFAULT_IMPORTS) { - log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); - return Either.right(ToscaError.GENERAL_ERROR); - } - - log.trace("start tosca export for {}", component.getUniqueId()); - ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); - - toscaTemplate.setMetadata(convertMetadata(component)); - toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); - Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); - if (ModelConverter.isAtomicComponent(component)) { - log.trace("convert component as node type"); - return convertNodeType(component, toscaTemplate, nodeTypes); - } else { - log.trace("convert component as topology template"); - return convertToscaTemplate(component, toscaTemplate); - } - - } - - private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) { - - Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component, - toscaNode); - if (importsRes.isRight()) { - return Either.right(importsRes.right().value()); - } - toscaNode = importsRes.left().value().left; - Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(component); - if (nodeTypesMapEither.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", - nodeTypesMapEither.right().value()); - return Either.right(nodeTypesMapEither.right().value()); - } - Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value(); - if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) - toscaNode.setNode_types(nodeTypesMap); - - Map<String, Component> componentCache = importsRes.left().value().right; - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); - return Either.right(ToscaError.GENERAL_ERROR); - } - Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); - - ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); - - Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes); - if (inputs.isRight()) { - return Either.right(inputs.right().value()); - } - topologyTemplate = inputs.left().value(); - - List<ComponentInstance> componentInstances = component.getComponentInstances(); - Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component - .getComponentInstancesProperties(); - List<GroupDefinition> groups = component.getGroups(); - if (componentInstances != null && !componentInstances.isEmpty()) { - - Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component, - componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate); - if (nodeTemplates.isRight()) { - return Either.right(nodeTemplates.right().value()); - } - log.debug("node templates converted"); - - topologyTemplate.setNode_templates(nodeTemplates.left().value()); - } - Map<String, ToscaGroupTemplate> groupsMap; - if (groups != null && !groups.isEmpty()) { - groupsMap = new HashMap<>(); - for (GroupDefinition group : groups) { - boolean addToTosca = true; - if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { - List<String> artifacts = group.getArtifacts(); - if (artifacts == null || artifacts.isEmpty()) { - addToTosca = false; - } - } - if (addToTosca) { - ToscaGroupTemplate toscaGroup = convertGroup(group); - groupsMap.put(group.getName(), toscaGroup); - } - - } - log.debug("groups converted"); - topologyTemplate.addGroups(groupsMap); - } - SubstitutionMapping substitutionMapping = new SubstitutionMapping(); - String toscaResourceName; - switch (component.getComponentType()) { - case RESOURCE: - toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() - .getMetadataDataDefinition()).getToscaResourceName(); - break; - case SERVICE: - toscaResourceName = SERVICE_NODE_TYPE_PREFIX - + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); - return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); - } - substitutionMapping.setNode_type(toscaResourceName); - - Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping); - if (capabilities.isRight()) { - return Either.right(capabilities.right().value()); - } - substitutionMapping = capabilities.left().value(); - - Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor - .convertSubstitutionMappingRequirements(originComponents, component, substitutionMapping); - if (requirements.isRight()) { - return Either.right(requirements.right().value()); - } - substitutionMapping = requirements.left().value(); - - topologyTemplate.setSubstitution_mappings(substitutionMapping); - - toscaNode.setTopology_template(topologyTemplate); - return Either.left(toscaNode); - } - - private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component, - ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) { - if (log.isDebugEnabled()) - log.debug("fillInputs for component {}", component.getUniqueId()); - List<InputDefinition> inputDef = component.getInputs(); - Map<String, ToscaProperty> inputs = new HashMap<>(); - - if (inputDef != null) { - inputDef.forEach(i -> { - ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); - inputs.put(i.getName(), property); - }); - if (!inputs.isEmpty()) { - topologyTemplate.setInputs(inputs); - } - } - return Either.left(topologyTemplate); - } - - private ToscaMetadata convertMetadata(Component component) { - return convertMetadata(component, false, null); - } - - private ToscaMetadata convertMetadata(Component component, boolean isInstance, - ComponentInstance componentInstance) { - ToscaMetadata toscaMetadata = new ToscaMetadata(); - toscaMetadata.setInvariantUUID(component.getInvariantUUID()); - toscaMetadata.setUUID(component.getUUID()); - toscaMetadata.setDescription(component.getDescription()); - toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); - - List<CategoryDefinition> categories = component.getCategories(); - CategoryDefinition categoryDefinition = categories.get(0); - toscaMetadata.setCategory(categoryDefinition.getName()); - - if (isInstance) { - toscaMetadata.setVersion(component.getVersion()); - toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID()); - if (componentInstance.getSourceModelInvariant() != null - && !componentInstance.getSourceModelInvariant().isEmpty()) { - toscaMetadata.setVersion(componentInstance.getComponentVersion()); - toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant()); - toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid()); - toscaMetadata.setSourceModelName(componentInstance.getSourceModelName()); - toscaMetadata.setName( - componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue()); - toscaMetadata.setDescription(componentInstance.getDescription()); - } - - } - switch (component.getComponentType()) { - case RESOURCE: - Resource resource = (Resource) component; - - if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { - toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue()); - } else - toscaMetadata.setType(resource.getResourceType().name()); - toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName()); - toscaMetadata.setResourceVendor(resource.getVendorName()); - toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); - toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber()); - break; - case SERVICE: - Service service = (Service) component; - toscaMetadata.setType(component.getComponentType().getValue()); - toscaMetadata.setServiceType(service.getServiceType()); - toscaMetadata.setServiceRole(service.getServiceRole()); - toscaMetadata.setEnvironmentContext(service.getEnvironmentContext()); - if (!isInstance) { - // DE268546 - toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming()); - toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming()); - toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy()); - } - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); - } - return toscaMetadata; - } - - private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component, - ToscaTemplate toscaTemplate) { - - if (null == DEFAULT_IMPORTS) { - log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); - return Either.right(ToscaError.GENERAL_ERROR); - } - - Map<String, Component> componentCache = new HashMap<>(); - - if (!ModelConverter.isAtomicComponent(component)) { - List<ComponentInstance> componentInstances = component.getComponentInstances(); - if (componentInstances != null && !componentInstances.isEmpty()) { - - List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null - ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports()); - - List<Triple<String, String, Component>> dependecies = new ArrayList<>(); - - Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); - - Map<String, Map<String, String>> importsListMember = new HashMap<>(); - Map<String, String> interfaceFiles = new HashMap<>(); - interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())); - StringBuilder keyNameBuilder = new StringBuilder(); - keyNameBuilder.append(component.getComponentType().toString().toLowerCase()); - keyNameBuilder.append("-"); - keyNameBuilder.append(component.getName()); - keyNameBuilder.append("-interface"); - importsListMember.put(keyNameBuilder.toString(), interfaceFiles); - additionalImports.add(importsListMember); - - componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci)); - originComponents.putAll(componentCache); - toscaTemplate.setDependencies(dependecies); - toscaTemplate.setImports(additionalImports); - } - } else { - log.debug("currently imports supported for VF and service only"); - } - return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache)); - } - - private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports, - List<Triple<String, String, Component>> dependecies, ComponentInstance ci) { - Map<String, String> files = new HashMap<>(); - Map<String, Map<String, String>> importsListMember = new HashMap<>(); - StringBuilder keyNameBuilder; - - Component componentRI = componentCache.get(ci.getComponentUid()); - if (componentRI == null) { - // all resource must be only once! - Either<Component, StorageOperationStatus> resource = toscaOperationFacade - .getToscaFullElement(ci.getComponentUid()); - if (resource.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } - Component fetchedComponent = resource.left().value(); - componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent); - componentRI = fetchedComponent; - - Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts(); - ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE); - if (artifactDefinition != null) { - String artifactName = artifactDefinition.getArtifactName(); - files.put(IMPORTS_FILE_KEY, artifactName); - keyNameBuilder = new StringBuilder(); - keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase()); - keyNameBuilder.append("-"); - keyNameBuilder.append(ci.getComponentName()); - importsListMember.put(keyNameBuilder.toString(), files); - imports.add(importsListMember); - dependecies.add(new ImmutableTriple<String, String, Component>(artifactName, - artifactDefinition.getEsId(), fetchedComponent)); - - if (!ModelConverter.isAtomicComponent(componentRI)) { - importsListMember = new HashMap<>(); - Map<String, String> interfaceFiles = new HashMap<>(); - interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName)); - keyNameBuilder.append("-interface"); - importsListMember.put(keyNameBuilder.toString(), interfaceFiles); - imports.add(importsListMember); - } - } - } - } - - public static String getInterfaceFilename(String artifactName) { - return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; - } - - private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode, - Map<String, ToscaNodeType> nodeTypes) { - log.debug("start convert node type for {}", component.getUniqueId()); - ToscaNodeType toscaNodeType = createNodeType(component); - - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); - return Either.right(ToscaError.GENERAL_ERROR); - } - - Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); - Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType, - dataTypes); - if (properties.isRight()) { - return Either.right(properties.right().value()); - } - toscaNodeType = properties.left().value(); - log.debug("Properties converted for {}", component.getUniqueId()); - - // Extracted to method for code reuse - return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); - } - - private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode, - Map<String, ToscaNodeType> nodeTypes) { - log.debug("start convert node type for {}", component.getUniqueId()); - ToscaNodeType toscaNodeType = createNodeType(component); - - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); - return Either.right(ToscaError.GENERAL_ERROR); - } - - Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); - - List<InputDefinition> inputDef = component.getInputs(); - Map<String, ToscaProperty> inputs = new HashMap<>(); - - if (inputDef != null) { - inputDef.forEach(i -> { - ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); - inputs.put(i.getName(), property); - }); - if (!inputs.isEmpty()) { - toscaNodeType.setProperties(inputs); - } - } - - // Extracted to method for code reuse - return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); - } - - private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode, - Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType, - Map<String, DataTypeDefinition> dataTypes) { - Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes); - if (capabilities.isRight()) { - return Either.right(capabilities.right().value()); - } - toscaNodeType = capabilities.left().value(); - log.debug("Capabilities converted for {}", component.getUniqueId()); - - Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component, - toscaNodeType); - if (requirements.isRight()) { - return Either.right(requirements.right().value()); - } - toscaNodeType = requirements.left().value(); - log.debug("Requirements converted for {}", component.getUniqueId()); - - String toscaResourceName; - switch (component.getComponentType()) { - case RESOURCE: - toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() - .getMetadataDataDefinition()).getToscaResourceName(); - break; - case SERVICE: - toscaResourceName = SERVICE_NODE_TYPE_PREFIX - + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); - break; - default: - log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); - return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); - } - - nodeTypes.put(toscaResourceName, toscaNodeType); - toscaNode.setNode_types(nodeTypes); - log.debug("finish convert node type for {}", component.getUniqueId()); - return Either.left(toscaNode); - } - - private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component, - List<ComponentInstance> componentInstances, - Map<String, List<ComponentInstanceProperty>> componentInstancesProperties, - Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes, - ToscaTopolgyTemplate topologyTemplate) { - - Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null; - log.debug("start convert topology template for {} for type {}", component.getUniqueId(), - component.getComponentType()); - Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>(); - Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs(); - - Map<String, ToscaGroupTemplate> groupsMap = null; - for (ComponentInstance componentInstance : componentInstances) { - ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); - nodeTemplate.setType(componentInstance.getToscaComponentName()); - - Either<Component, Boolean> originComponentRes = capabiltyRequirementConvertor - .getOriginComponent(componentCache, componentInstance); - if (originComponentRes.isRight()) { - convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); - break; - } - Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component, - componentInstance, component.getComponentInstancesRelations(), nodeTemplate, - originComponentRes.left().value()); - if (requirements.isRight()) { - convertNodeTemplatesRes = Either.right(requirements.right().value()); - break; - } - String instanceUniqueId = componentInstance.getUniqueId(); - log.debug("Component instance Requirements converted for instance {}", instanceUniqueId); - - nodeTemplate = requirements.left().value(); - - Component componentOfInstance = componentCache.get(componentInstance.getActualComponentUid()); - nodeTemplate.setMetadata(convertMetadata(componentOfInstance, true, componentInstance)); - - Either<ToscaNodeTemplate, ToscaError> capabilities = capabiltyRequirementConvertor - .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate); - if (capabilities.isRight()) { - convertNodeTemplatesRes = Either.right(requirements.right().value()); - break; - } - log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId); - - nodeTemplate = capabilities.left().value(); - Map<String, Object> props = new HashMap<>(); - - if (componentOfInstance.getComponentType() == ComponentTypeEnum.RESOURCE) { - // Adds the properties of parent component to map - addPropertiesOfParentComponent(dataTypes, componentInstance, componentOfInstance, props); - } - - if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) { - addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance, - instanceUniqueId, props); - } - - if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) { - addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId, - props); - } - if (props != null && !props.isEmpty()) { - nodeTemplate.setProperties(props); - } - - List<GroupInstance> groupInstances = componentInstance.getGroupInstances(); - if (groupInstances != null) { - if (groupsMap == null) { - groupsMap = new HashMap<>(); - } - for (GroupInstance groupInst : groupInstances) { - boolean addToTosca = true; - - List<String> artifacts = groupInst.getArtifacts(); - if (artifacts == null || artifacts.isEmpty()) { - addToTosca = false; - } - - if (addToTosca) { - ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst); - groupsMap.put(groupInst.getName(), toscaGroup); - } - } - } - - nodeTemplates.put(componentInstance.getName(), nodeTemplate); - } - if (groupsMap != null) { - log.debug("instance groups added"); - topologyTemplate.addGroups(groupsMap); - } - - if (convertNodeTemplatesRes == null) { - convertNodeTemplatesRes = Either.left(nodeTemplates); - } - log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), - component.getComponentType()); - return convertNodeTemplatesRes; - } - - private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes, - Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance, - String instanceUniqueId, Map<String, Object> props) { - - List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId); - if (instanceInputsList != null) { - instanceInputsList.forEach(input -> { - - Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty() - ? input.getValue() : input.getDefaultValue(); - convertAndAddValue(dataTypes, componentInstance, props, input, supplier); - }); - } - } - - private void addPropertiesOfComponentInstance( - Map<String, List<ComponentInstanceProperty>> componentInstancesProperties, - Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId, - Map<String, Object> props) { - - if (!MapUtils.isEmpty(componentInstancesProperties)) { - componentInstancesProperties.get(instanceUniqueId).stream() - // Collects filtered properties to List - .collect(Collectors.toList()).stream() - // Converts and adds each value to property map - .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, - () -> prop.getValue())); - } - } - - private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes, - ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) { - - List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties(); - if (!CollectionUtils.isEmpty(componentProperties)) { - componentProperties.stream() - // Filters out properties with empty default values - .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue())) - // Collects filtered properties to List - .collect(Collectors.toList()).stream() - // Converts and adds each value to property map - .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, - () -> prop.getDefaultValue())); - } - } - - /** - * @param dataTypes - * @param componentInstance - * @param props - * @param prop - * @param supplier - */ - private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, - Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) { - Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier); - if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) { - props.put(prop.getName(), convertedValue); - } - } - - private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, - ComponentInstance componentInstance, T input, Supplier<String> supplier) { - log.debug("Convert property or input value {} for instance {}", input.getName(), - componentInstance.getUniqueId()); - String propertyType = input.getType(); - String innerType = null; - if (input.getSchema() != null && input.getSchema().getProperty() != null) { - innerType = input.getSchema().getProperty().getType(); - } - return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes); - } - - private ToscaGroupTemplate convertGroup(GroupDefinition group) { - - ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); - Map<String, String> members = group.getMembers(); - if (members != null) - toscaGroup.setMembers(new ArrayList<String>(members.keySet())); - - Supplier<String> supplGroupType = () -> group.getType(); - Supplier<String> supplDescription = () -> group.getDescription(); - Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties(); - Supplier<String> supplgroupName = () -> group.getName(); - Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID(); - Supplier<String> supplGroupUUID = () -> group.getGroupUUID(); - Supplier<String> supplVersion = () -> group.getVersion(); - - IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, - supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); - toscaGroup.setMetadata(toscaMetadata); - return toscaGroup; - } - - private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) { - ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); - - Supplier<String> supplGroupType = () -> groupInstance.getType(); - Supplier<String> supplDescription = () -> groupInstance.getDescription(); - Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance - .convertToGroupInstancesProperties(); - Supplier<String> supplgroupName = () -> groupInstance.getGroupName(); - Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID(); - Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID(); - Supplier<String> supplVersion = () -> groupInstance.getVersion(); - - IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, - supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); - - toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID()); - toscaGroup.setMetadata(toscaMetadata); - return toscaGroup; - } - - private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props, - Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID, - Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) { - boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false; - toscaGroup.setType(groupType.get()); - - IToscaMetadata toscaMetadata; - if (!isVfModule) { - toscaMetadata = new ToscaMetadata(); - } else { - toscaMetadata = new VfModuleToscaMetadata(); - - Map<String, Object> properties = fillGroupProperties(props.get()); - if (!properties.containsKey(VF_MODULE_DESC_KEY) - || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))) { - properties.put(VF_MODULE_DESC_KEY, description.get()); - } - toscaGroup.setProperties(properties); - } - toscaMetadata.setName(groupName.get()); - toscaMetadata.setInvariantUUID(invariantUUID.get()); - toscaMetadata.setUUID(groupUUID.get()); - toscaMetadata.setVersion(version.get()); - return toscaMetadata; - } - - private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) { - Map<String, Object> properties = new HashMap<>(); - if (groupProps != null) { - for (GroupProperty gp : groupProps) { - if (gp.getName().equals(Constants.IS_BASE)) { - Boolean isBase = Boolean.parseBoolean(gp.getValue()); - String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION; - properties.put(VF_MODULE_TYPE_KEY, type); - } else { - Object value = null; - String type = gp.getType(); - - switch (type) { - case "integer": - if (gp.getValue() != null) { - value = Integer.valueOf(gp.getValue()); - } - break; - case "boolean": - if (gp.getValue() != null) { - value = Boolean.valueOf(gp.getValue()); - } - break; - - default: - value = gp.getValue(); - break; - } - properties.put(gp.getName(), value); - } - } - } - return properties; - } - - private ToscaNodeType createNodeType(Component component) { - ToscaNodeType toscaNodeType = new ToscaNodeType(); - if (ModelConverter.isAtomicComponent(component)) { - if (((Resource) component).getDerivedFrom() != null) { - toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0)); - } - toscaNodeType.setDescription(component.getDescription()); // or - // name?? - } else { - String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType() - : "tosca.nodes.Root"; - toscaNodeType.setDerived_from(derivedFrom); - } - return toscaNodeType; - } - - private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Component container) { - - Map<String, ToscaNodeType> nodeTypesMap = null; - Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap); - - List<ComponentInstance> componetInstances = container.getComponentInstances(); - - if (componetInstances == null || componetInstances.isEmpty()) - return res; - Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>(); - List<ComponentInstance> proxyInst = componetInstances.stream() - .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name())) - .collect(Collectors.toList()); - if (proxyInst != null && !proxyInst.isEmpty()) { - for (ComponentInstance inst : proxyInst) { - serviceProxyInstanceList.put(inst.getToscaComponentName(), inst); - } - } - - if (serviceProxyInstanceList.isEmpty()) - return res; - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreCapabilities(false); - filter.setIgnoreComponentInstances(false); - Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade - .getLatestByName("serviceProxy"); - if (serviceProxyOrigin.isRight()) { - log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", - serviceProxyOrigin.right().value()); - return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); - } - Component origComponent = serviceProxyOrigin.left().value(); - - nodeTypesMap = new HashMap<>(); - for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) { - Component serviceComponent = null; - ComponentParametersView componentParametersView = new ComponentParametersView(); - componentParametersView.disableAll(); - componentParametersView.setIgnoreCategories(false); - Either<Component, StorageOperationStatus> service = toscaOperationFacade - .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView); - if (service.isRight()) { - log.debug("Failed to fetch resource with id {} for instance {}"); - } else - serviceComponent = service.left().value(); - - ToscaNodeType toscaNodeType = createProxyNodeType(origComponent, serviceComponent, entryProxy.getValue()); - nodeTypesMap.put(entryProxy.getKey(), toscaNodeType); - } - - return Either.left(nodeTypesMap); - } - - private ToscaNodeType createProxyNodeType(Component origComponent, Component proxyComponent, - ComponentInstance instance) { - ToscaNodeType toscaNodeType = new ToscaNodeType(); - String derivedFrom = ((Resource) origComponent).getToscaResourceName(); - - toscaNodeType.setDerived_from(derivedFrom); - Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); - if (dataTypesEither.isRight()) { - log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); - } - Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); - Map<String, ToscaCapability> capabilities = this.capabiltyRequirementConvertor - .convertProxyCapabilities(origComponent, proxyComponent, instance, dataTypes); - - toscaNodeType.setCapabilities(capabilities); - - return toscaNodeType; - } - - private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component, - ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations, - ToscaNodeTemplate nodeTypeTemplate, Component originComponent) { - - List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); - if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements)) { - log.debug("Failed to convert component instance requirements for the component instance {}. ", - componentInstance.getName()); - return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); - } - if (!toscaRequirements.isEmpty()) { - nodeTypeTemplate.setRequirements(toscaRequirements); - } - log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName()); - return Either.left(nodeTypeTemplate); - } - - private boolean addRequirements(Component component, ComponentInstance componentInstance, - List<RequirementCapabilityRelDef> relations, Component originComponent, - List<Map<String, ToscaTemplateRequirement>> toscaRequirements) { - boolean result; - List<RequirementCapabilityRelDef> filteredRelations = relations.stream() - .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList()); - if (CollectionUtils.isEmpty(filteredRelations)) { - result = true; - } else { - result = !filteredRelations.stream().filter(rel -> !addRequirement(componentInstance, originComponent, - component.getComponentInstances(), rel, toscaRequirements)).findFirst().isPresent(); - } - return result; - } - - private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent, - List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel, - List<Map<String, ToscaTemplateRequirement>> toscaRequirements) { - - boolean result = true; - Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements(); - RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation(); - Either<Component, StorageOperationStatus> getOriginRes = null; - Optional<RequirementDefinition> reqOpt = null; - Component toOriginComponent = null; - Optional<CapabilityDefinition> cap = null; - - ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId())) - .findFirst().orElse(null); - if (toInstance == null) { - log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(), - rel.getToNode()); - result = false; - } - if (result) { - reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, toInstance.getUniqueId()); - if (!reqOpt.isPresent()) { - log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}", - reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId()); - result = false; - } - } - if (result) { - ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreComponentInstances(false); - filter.setIgnoreCapabilities(false); - getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter); - if (getOriginRes.isRight()) { - log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}", - reqOpt.get().getName(), toInstance.getActualComponentUid()); - result = false; - } - } - if (result) { - toOriginComponent = getOriginRes.left().value(); - cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream() - .filter(c -> c.getName().equals(reqAndRelationshipPair.getCapability())).findFirst(); - if (!cap.isPresent()) { - cap = findCapability(reqMap, reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get(), fromInstance); - if(!cap.isPresent()){ - result = false; - log.debug("Failed to find a capability with name {} on a component with uniqueId {}", - reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); - } - } - } - if (result) { - result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, cap.get(), - reqOpt.get(), reqAndRelationshipPair, toInstance); - } - return result; - } - - private Optional<CapabilityDefinition> findCapability(Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement, ComponentInstance fromInstance) { - Optional<CapabilityDefinition> cap = Optional.empty(); - Optional<RequirementDefinition> findAny = reqMap.values().stream().flatMap(e -> e.stream()).filter(e -> e.getName().equals(reqAndRelationshipPair.getRequirement())).findAny(); - if (findAny.isPresent()) { - RequirementDefinition reqDefinition = findAny.get(); - cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(reqDefinition.getCapability())).findFirst(); - if (!cap.isPresent()) { - log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); - } - } - return cap; - } - - private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance) { - boolean result = true; - Either<String, Boolean> buildReqNameRes = null; - Either<String, Boolean> buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, - toOriginComponent, capability.getPath(), reqAndRelationshipPair.getCapability()); - if (buildCapNameRes.isRight()) { - log.debug( - "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}", - reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); - result = false; - } - if (result) { - buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, fromOriginComponent, - requirement.getPath(), reqAndRelationshipPair.getRequirement()); - if (buildReqNameRes.isRight()) { - log.debug( - "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}", - reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId()); - result = false; - } - } - if (result) { - ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement(); - Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>(); - toscaRequirement.setNode(toInstance.getName()); - toscaRequirement.setCapability(buildCapNameRes.left().value()); - toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement); - toscaRequirements.add(toscaReqMap); - } - return result; - } - - private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String toInstanceId) { - for(List<RequirementDefinition> reqList: reqMap.values()){ - Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, toInstanceId)).findFirst(); - if(reqOpt.isPresent()){ - return reqOpt; - } - } - return Optional.empty(); - } - - /** - * Allows detecting the requirement belonging to the received relationship - * The detection logic is: A requirement belongs to a relationship IF 1.The - * name of the requirement equals to the "requirement" field of the - * relation; AND 2. In case of a non-atomic resource, OwnerId of the - * requirement equals to requirementOwnerId of the relation OR uniqueId of - * toInstance equals to capabilityOwnerId of the relation - * - * @param fromOriginComponent - * @param reqAndRelationshipPair - * @param requirement - * @param toInstanceId - * @return - */ - private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) { - if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())) - return false; - if (!ModelConverter.isAtomicComponent(originComponent)) - return isRequirementBelongToOwner(reqAndRelationshipPair, requirement, toInstanceId); - return true; - } - - private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String toInstanceId) { - return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || StringUtils.equals(toInstanceId, reqAndRelationshipPair.getCapabilityOwnerId()); - } - - private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, - SubstitutionMapping substitutionMappings) { - - Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings); - Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabiltyRequirementConvertor - .convertSubstitutionMappingCapabilities(originComponents, component); - if (toscaCapabilitiesRes.isRight()) { - result = Either.right(toscaCapabilitiesRes.right().value()); - log.error("Failed convert capabilities for the component {}. ", component.getName()); - } else if (MapUtils.isNotEmpty(toscaCapabilitiesRes.left().value())) { - substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value()); - log.debug("Finish convert capabilities for the component {}. ", component.getName()); - } - log.debug("Finished to convert capabilities for the component {}. ", component.getName()); - return result; - } - - private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType, - Map<String, DataTypeDefinition> dataTypes) { - Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, - dataTypes); - if (!toscaCapabilities.isEmpty()) { - nodeType.setCapabilities(toscaCapabilities); - } - log.debug("Finish convert Capabilities for node type"); - - return Either.left(nodeType); - } - - private static class CustomRepresenter extends Representer { - public CustomRepresenter() { - super(); - // null representer is exceptional and it is stored as an instance - // variable. - this.nullRepresenter = new RepresentNull(); - - } - - @Override - protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, - Tag customTag) { - if (propertyValue == null) { - return null; - } else { - // skip not relevant for Tosca property - if ("dependencies".equals(property.getName())) { - return null; - } - NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); - - return "_defaultp_".equals(property.getName()) - ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; - } - } - - @Override - protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { - // remove the bean type from the output yaml (!! ...) - if (!classTags.containsKey(javaBean.getClass())) - addClassTag(javaBean.getClass(), Tag.MAP); - - return super.representJavaBean(properties, javaBean); - } - - private class RepresentNull implements Represent { - @Override - public Node representData(Object data) { - // possible values are here http://yaml.org/type/null.html - return representScalar(Tag.NULL, ""); - } - } - } - - private static class UnsortedPropertyUtils extends PropertyUtils { - @Override - protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) - throws IntrospectionException { - Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values(); - return new LinkedHashSet<>(fields); - } - } + @Autowired + private ApplicationDataTypeCache dataTypeCache; + + @Autowired + private ToscaOperationFacade toscaOperationFacade; + @Autowired + private CapabiltyRequirementConvertor capabiltyRequirementConvertor; + private PropertyConvertor propertyConvertor = PropertyConvertor.getInstance(); + + private static final Logger log = LoggerFactory.getLogger(ToscaExportHandler.class); + + public static final String TOSCA_VERSION = "tosca_simple_yaml_1_1"; + public static final String SERVICE_NODE_TYPE_PREFIX = "org.openecomp.service."; + public static final String IMPORTS_FILE_KEY = "file"; + public static final String TOSCA_TEMPLATE_NAME = "-template.yml"; + public static final String TOSCA_INTERFACE_NAME = "-interface.yml"; + public static final String ASSET_TOSCA_TEMPLATE = "assettoscatemplate"; + public static final String VF_MODULE_TYPE_KEY = "vf_module_type"; + public static final String VF_MODULE_DESC_KEY = "vf_module_description"; + public static final String VOLUME_GROUP_KEY = "volume_group"; + public static final String VF_MODULE_TYPE_BASE = "Base"; + public static final String VF_MODULE_TYPE_EXPANSION = "Expansion"; + private static final String FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION = "convertToToscaTemplate - failed to get Default Imports section from configuration"; + private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}"; + protected static final List<Map<String, Map<String, String>>> DEFAULT_IMPORTS = ConfigurationManager + .getConfigurationManager().getConfiguration().getDefaultImports(); + + public Either<ToscaRepresentation, ToscaError> exportComponent(Component component) { + + Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertToToscaTemplate(component); + if (toscaTemplateRes.isRight()) { + return Either.right(toscaTemplateRes.right().value()); + } + + ToscaTemplate toscaTemplate = toscaTemplateRes.left().value(); + ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); + return Either.left(toscaRepresentation); + } + + public Either<ToscaRepresentation, ToscaError> exportComponentInterface(Component component) { + if (null == DEFAULT_IMPORTS) { + log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); + return Either.right(ToscaError.GENERAL_ERROR); + } + + ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); + toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); + Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); + Either<ToscaTemplate, ToscaError> toscaTemplateRes = convertInterfaceNodeType(component, toscaTemplate, + nodeTypes); + if (toscaTemplateRes.isRight()) { + return Either.right(toscaTemplateRes.right().value()); + } + + toscaTemplate = toscaTemplateRes.left().value(); + ToscaRepresentation toscaRepresentation = this.createToscaRepresentation(toscaTemplate); + return Either.left(toscaRepresentation); + } + + public ToscaRepresentation createToscaRepresentation(ToscaTemplate toscaTemplate) { + CustomRepresenter representer = new CustomRepresenter(); + DumperOptions options = new DumperOptions(); + options.setAllowReadOnlyProperties(false); + options.setPrettyFlow(true); + + options.setDefaultFlowStyle(FlowStyle.FLOW); + options.setCanonical(false); + + representer.addClassTag(toscaTemplate.getClass(), Tag.MAP); + + representer.setPropertyUtils(new UnsortedPropertyUtils()); + Yaml yaml = new Yaml(representer, options); + + String yamlAsString = yaml.dumpAsMap(toscaTemplate); + + StringBuilder sb = new StringBuilder(); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader()); + sb.append(yamlAsString); + sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter()); + + ToscaRepresentation toscaRepresentation = new ToscaRepresentation(); + toscaRepresentation.setMainYaml(sb.toString()); + toscaRepresentation.setDependencies(toscaTemplate.getDependencies()); + + return toscaRepresentation; + } + + public Either<ToscaTemplate, ToscaError> getDependencies(Component component) { + ToscaTemplate toscaTemplate = new ToscaTemplate(null); + Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports = fillImports(component, + toscaTemplate); + if (fillImports.isRight()) { + return Either.right(fillImports.right().value()); + } + return Either.left(fillImports.left().value().left); + } + + private Either<ToscaTemplate, ToscaError> convertToToscaTemplate(Component component) { + if (null == DEFAULT_IMPORTS) { + log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); + return Either.right(ToscaError.GENERAL_ERROR); + } + + log.trace("start tosca export for {}", component.getUniqueId()); + ToscaTemplate toscaTemplate = new ToscaTemplate(TOSCA_VERSION); + + toscaTemplate.setMetadata(convertMetadata(component)); + toscaTemplate.setImports(new ArrayList<>(DEFAULT_IMPORTS)); + Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); + if (ModelConverter.isAtomicComponent(component)) { + log.trace("convert component as node type"); + return convertNodeType(component, toscaTemplate, nodeTypes); + } else { + log.trace("convert component as topology template"); + return convertToscaTemplate(component, toscaTemplate); + } + + } + + private Either<ToscaTemplate, ToscaError> convertToscaTemplate(Component component, ToscaTemplate toscaNode) { + + Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> importsRes = fillImports(component, + toscaNode); + if (importsRes.isRight()) { + return Either.right(importsRes.right().value()); + } + toscaNode = importsRes.left().value().left; + Map<String, Component> componentCache = importsRes.left().value().right; + Either<Map<String, ToscaNodeType>, ToscaError> nodeTypesMapEither = createProxyNodeTypes(componentCache , component ); + if (nodeTypesMapEither.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", + nodeTypesMapEither.right().value()); + return Either.right(nodeTypesMapEither.right().value()); + } + Map<String, ToscaNodeType> nodeTypesMap = nodeTypesMapEither.left().value(); + if (nodeTypesMap != null && !nodeTypesMap.isEmpty()) + toscaNode.setNode_types(nodeTypesMap); + + + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); + + ToscaTopolgyTemplate topologyTemplate = new ToscaTopolgyTemplate(); + + Either<ToscaTopolgyTemplate, ToscaError> inputs = fillInputs(component, topologyTemplate, dataTypes); + if (inputs.isRight()) { + return Either.right(inputs.right().value()); + } + topologyTemplate = inputs.left().value(); + + List<ComponentInstance> componentInstances = component.getComponentInstances(); + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component + .getComponentInstancesProperties(); + List<GroupDefinition> groups = component.getGroups(); + if (componentInstances != null && !componentInstances.isEmpty()) { + + Either<Map<String, ToscaNodeTemplate>, ToscaError> nodeTemplates = convertNodeTemplates(component, + componentInstances, componentInstancesProperties, componentCache, dataTypes, topologyTemplate); + if (nodeTemplates.isRight()) { + return Either.right(nodeTemplates.right().value()); + } + log.debug("node templates converted"); + + topologyTemplate.setNode_templates(nodeTemplates.left().value()); + } + Map<String, ToscaGroupTemplate> groupsMap; + if (groups != null && !groups.isEmpty()) { + groupsMap = new HashMap<>(); + for (GroupDefinition group : groups) { + boolean addToTosca = true; + if (group.getType().equals(Constants.DEFAULT_GROUP_VF_MODULE)) { + List<String> artifacts = group.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + addToTosca = false; + } + } + if (addToTosca) { + ToscaGroupTemplate toscaGroup = convertGroup(group); + groupsMap.put(group.getName(), toscaGroup); + } + + } + log.debug("groups converted"); + topologyTemplate.addGroups(groupsMap); + } + SubstitutionMapping substitutionMapping = new SubstitutionMapping(); + String toscaResourceName; + switch (component.getComponentType()) { + case RESOURCE: + toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() + .getMetadataDataDefinition()).getToscaResourceName(); + break; + case SERVICE: + toscaResourceName = SERVICE_NODE_TYPE_PREFIX + + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + substitutionMapping.setNode_type(toscaResourceName); + + Either<SubstitutionMapping, ToscaError> capabilities = convertCapabilities(component, substitutionMapping, componentCache); + if (capabilities.isRight()) { + return Either.right(capabilities.right().value()); + } + substitutionMapping = capabilities.left().value(); + + Either<SubstitutionMapping, ToscaError> requirements = capabiltyRequirementConvertor + .convertSubstitutionMappingRequirements(componentCache, component, substitutionMapping); + if (requirements.isRight()) { + return Either.right(requirements.right().value()); + } + substitutionMapping = requirements.left().value(); + + topologyTemplate.setSubstitution_mappings(substitutionMapping); + + toscaNode.setTopology_template(topologyTemplate); + return Either.left(toscaNode); + } + + private Either<ToscaTopolgyTemplate, ToscaError> fillInputs(Component component, + ToscaTopolgyTemplate topologyTemplate, Map<String, DataTypeDefinition> dataTypes) { + if (log.isDebugEnabled()) + log.debug("fillInputs for component {}", component.getUniqueId()); + List<InputDefinition> inputDef = component.getInputs(); + Map<String, ToscaProperty> inputs = new HashMap<>(); + + if (inputDef != null) { + inputDef.forEach(i -> { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); + inputs.put(i.getName(), property); + }); + if (!inputs.isEmpty()) { + topologyTemplate.setInputs(inputs); + } + } + return Either.left(topologyTemplate); + } + + private ToscaMetadata convertMetadata(Component component) { + return convertMetadata(component, false, null); + } + + private ToscaMetadata convertMetadata(Component component, boolean isInstance, + ComponentInstance componentInstance) { + ToscaMetadata toscaMetadata = new ToscaMetadata(); + toscaMetadata.setInvariantUUID(component.getInvariantUUID()); + toscaMetadata.setUUID(component.getUUID()); + toscaMetadata.setDescription(component.getDescription()); + toscaMetadata.setName(component.getComponentMetadataDefinition().getMetadataDataDefinition().getName()); + + List<CategoryDefinition> categories = component.getCategories(); + CategoryDefinition categoryDefinition = categories.get(0); + toscaMetadata.setCategory(categoryDefinition.getName()); + + if (isInstance) { + toscaMetadata.setVersion(component.getVersion()); + toscaMetadata.setCustomizationUUID(componentInstance.getCustomizationUUID()); + if (componentInstance.getSourceModelInvariant() != null + && !componentInstance.getSourceModelInvariant().isEmpty()) { + toscaMetadata.setVersion(componentInstance.getComponentVersion()); + toscaMetadata.setSourceModelInvariant(componentInstance.getSourceModelInvariant()); + toscaMetadata.setSourceModelUuid(componentInstance.getSourceModelUuid()); + toscaMetadata.setSourceModelName(componentInstance.getSourceModelName()); + toscaMetadata.setName( + componentInstance.getSourceModelName() + " " + OriginTypeEnum.ServiceProxy.getDisplayValue()); + toscaMetadata.setDescription(componentInstance.getDescription()); + } + + } + switch (component.getComponentType()) { + case RESOURCE: + Resource resource = (Resource) component; + + if (isInstance && componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) { + toscaMetadata.setType(componentInstance.getOriginType().getDisplayValue()); + } else + toscaMetadata.setType(resource.getResourceType().name()); + toscaMetadata.setSubcategory(categoryDefinition.getSubcategories().get(0).getName()); + toscaMetadata.setResourceVendor(resource.getVendorName()); + toscaMetadata.setResourceVendorRelease(resource.getVendorRelease()); + toscaMetadata.setResourceVendorModelNumber(resource.getResourceVendorModelNumber()); + break; + case SERVICE: + Service service = (Service) component; + toscaMetadata.setType(component.getComponentType().getValue()); + toscaMetadata.setServiceType(service.getServiceType()); + toscaMetadata.setServiceRole(service.getServiceRole()); + toscaMetadata.setEnvironmentContext(service.getEnvironmentContext()); + if (!isInstance) { + // DE268546 + toscaMetadata.setServiceEcompNaming(((Service) component).isEcompGeneratedNaming()); + toscaMetadata.setEcompGeneratedNaming(((Service) component).isEcompGeneratedNaming()); + toscaMetadata.setNamingPolicy(((Service) component).getNamingPolicy()); + } + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); + } + return toscaMetadata; + } + + private Either<ImmutablePair<ToscaTemplate, Map<String, Component>>, ToscaError> fillImports(Component component, + ToscaTemplate toscaTemplate) { + + if (null == DEFAULT_IMPORTS) { + log.debug(FAILED_TO_GET_DEFAULT_IMPORTS_CONFIGURATION); + return Either.right(ToscaError.GENERAL_ERROR); + } + Map<String, Component> componentCache = new HashMap<>(); + + if (!ModelConverter.isAtomicComponent(component)) { + List<ComponentInstance> componentInstances = component.getComponentInstances(); + if (componentInstances != null && !componentInstances.isEmpty()) { + + List<Map<String, Map<String, String>>> additionalImports = toscaTemplate.getImports() == null + ? new ArrayList<>(DEFAULT_IMPORTS) : new ArrayList<>(toscaTemplate.getImports()); + + List<Triple<String, String, Component>> dependecies = new ArrayList<>(); + + Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE); + + Map<String, Map<String, String>> importsListMember = new HashMap<>(); + Map<String, String> interfaceFiles = new HashMap<>(); + interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactDefinition.getArtifactName())); + StringBuilder keyNameBuilder = new StringBuilder(); + keyNameBuilder.append(component.getComponentType().toString().toLowerCase()); + keyNameBuilder.append("-"); + keyNameBuilder.append(component.getName()); + keyNameBuilder.append("-interface"); + importsListMember.put(keyNameBuilder.toString(), interfaceFiles); + additionalImports.add(importsListMember); + + componentInstances.forEach(ci -> createDependency(componentCache, additionalImports, dependecies, ci)); + toscaTemplate.setDependencies(dependecies); + toscaTemplate.setImports(additionalImports); + } + } else { + log.debug("currently imports supported for VF and service only"); + } + return Either.left(new ImmutablePair<ToscaTemplate, Map<String, Component>>(toscaTemplate, componentCache)); + } + + private void createDependency(Map<String, Component> componentCache, List<Map<String, Map<String, String>>> imports, + List<Triple<String, String, Component>> dependecies, ComponentInstance ci) { + Map<String, String> files = new HashMap<>(); + Map<String, Map<String, String>> importsListMember = new HashMap<>(); + StringBuilder keyNameBuilder; + + Component componentRI = componentCache.get(ci.getComponentUid()); + if (componentRI == null) { + // all resource must be only once! + Either<Component, StorageOperationStatus> resource = toscaOperationFacade + .getToscaFullElement(ci.getComponentUid()); + if ((resource.isRight()) && (log.isDebugEnabled())) { + log.debug("Failed to fetch resource with id {} for instance {}",ci.getComponentUid() ,ci.getUniqueId()); + return ; + } + + Component fetchedComponent = resource.left().value(); + componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent); + + if (ci.getOriginType() == OriginTypeEnum.ServiceProxy){ + Either<Component, StorageOperationStatus> sourceService = toscaOperationFacade + .getToscaFullElement(ci.getSourceModelUid()); + if (sourceService.isRight() && (log.isDebugEnabled())) { + log.debug("Failed to fetch source service with id {} for proxy {}", ci.getSourceModelUid(), ci.getUniqueId()); + } + Component fetchedSource = sourceService.left().value(); + componentCache.put(fetchedSource.getUniqueId(), fetchedSource); + } + + componentRI = fetchedComponent; + + Map<String, ArtifactDefinition> toscaArtifacts = componentRI.getToscaArtifacts(); + ArtifactDefinition artifactDefinition = toscaArtifacts.get(ASSET_TOSCA_TEMPLATE); + if (artifactDefinition != null) { + String artifactName = artifactDefinition.getArtifactName(); + files.put(IMPORTS_FILE_KEY, artifactName); + keyNameBuilder = new StringBuilder(); + keyNameBuilder.append(fetchedComponent.getComponentType().toString().toLowerCase()); + keyNameBuilder.append("-"); + keyNameBuilder.append(ci.getComponentName()); + importsListMember.put(keyNameBuilder.toString(), files); + imports.add(importsListMember); + dependecies.add(new ImmutableTriple<String, String, Component>(artifactName, + artifactDefinition.getEsId(), fetchedComponent)); + + if (!ModelConverter.isAtomicComponent(componentRI)) { + importsListMember = new HashMap<>(); + Map<String, String> interfaceFiles = new HashMap<>(); + interfaceFiles.put(IMPORTS_FILE_KEY, getInterfaceFilename(artifactName)); + keyNameBuilder.append("-interface"); + importsListMember.put(keyNameBuilder.toString(), interfaceFiles); + imports.add(importsListMember); + } + } + } + } + + public static String getInterfaceFilename(String artifactName) { + return artifactName.substring(0, artifactName.lastIndexOf('.')) + ToscaExportHandler.TOSCA_INTERFACE_NAME; + } + + private Either<ToscaTemplate, ToscaError> convertNodeType(Component component, ToscaTemplate toscaNode, + Map<String, ToscaNodeType> nodeTypes) { + log.debug("start convert node type for {}", component.getUniqueId()); + ToscaNodeType toscaNodeType = createNodeType(component); + + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + + Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); + Either<ToscaNodeType, ToscaError> properties = propertyConvertor.convertProperties(component, toscaNodeType, + dataTypes); + if (properties.isRight()) { + return Either.right(properties.right().value()); + } + toscaNodeType = properties.left().value(); + log.debug("Properties converted for {}", component.getUniqueId()); + + // Extracted to method for code reuse + return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); + } + + private Either<ToscaTemplate, ToscaError> convertInterfaceNodeType(Component component, ToscaTemplate toscaNode, + Map<String, ToscaNodeType> nodeTypes) { + log.debug("start convert node type for {}", component.getUniqueId()); + ToscaNodeType toscaNodeType = createNodeType(component); + + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + + Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); + + List<InputDefinition> inputDef = component.getInputs(); + Map<String, ToscaProperty> inputs = new HashMap<>(); + + if (inputDef != null) { + inputDef.forEach(i -> { + ToscaProperty property = propertyConvertor.convertProperty(dataTypes, i, false); + inputs.put(i.getName(), property); + }); + if (!inputs.isEmpty()) { + toscaNodeType.setProperties(inputs); + } + } + + // Extracted to method for code reuse + return convertReqCapAndTypeName(component, toscaNode, nodeTypes, toscaNodeType, dataTypes); + } + + private Either<ToscaTemplate, ToscaError> convertReqCapAndTypeName(Component component, ToscaTemplate toscaNode, + Map<String, ToscaNodeType> nodeTypes, ToscaNodeType toscaNodeType, + Map<String, DataTypeDefinition> dataTypes) { + Either<ToscaNodeType, ToscaError> capabilities = convertCapabilities(component, toscaNodeType, dataTypes); + if (capabilities.isRight()) { + return Either.right(capabilities.right().value()); + } + toscaNodeType = capabilities.left().value(); + log.debug("Capabilities converted for {}", component.getUniqueId()); + + Either<ToscaNodeType, ToscaError> requirements = capabiltyRequirementConvertor.convertRequirements(component, + toscaNodeType); + if (requirements.isRight()) { + return Either.right(requirements.right().value()); + } + toscaNodeType = requirements.left().value(); + log.debug("Requirements converted for {}", component.getUniqueId()); + + String toscaResourceName; + switch (component.getComponentType()) { + case RESOURCE: + toscaResourceName = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition() + .getMetadataDataDefinition()).getToscaResourceName(); + break; + case SERVICE: + toscaResourceName = SERVICE_NODE_TYPE_PREFIX + + component.getComponentMetadataDefinition().getMetadataDataDefinition().getSystemName(); + break; + default: + log.debug(NOT_SUPPORTED_COMPONENT_TYPE, component.getComponentType()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + + nodeTypes.put(toscaResourceName, toscaNodeType); + toscaNode.setNode_types(nodeTypes); + log.debug("finish convert node type for {}", component.getUniqueId()); + return Either.left(toscaNode); + } + + private Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplates(Component component, + List<ComponentInstance> componentInstances, + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties, + Map<String, Component> componentCache, Map<String, DataTypeDefinition> dataTypes, + ToscaTopolgyTemplate topologyTemplate) { + + Either<Map<String, ToscaNodeTemplate>, ToscaError> convertNodeTemplatesRes = null; + log.debug("start convert topology template for {} for type {}", component.getUniqueId(), + component.getComponentType()); + Map<String, ToscaNodeTemplate> nodeTemplates = new HashMap<>(); + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = component.getComponentInstancesInputs(); + + Map<String, ToscaGroupTemplate> groupsMap = null; + for (ComponentInstance componentInstance : componentInstances) { + ToscaNodeTemplate nodeTemplate = new ToscaNodeTemplate(); + nodeTemplate.setType(componentInstance.getToscaComponentName()); + + Either<Component, Boolean> originComponentRes = capabiltyRequirementConvertor + .getOriginComponent(componentCache, componentInstance); + if (originComponentRes.isRight()) { + convertNodeTemplatesRes = Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + break; + } + Either<ToscaNodeTemplate, ToscaError> requirements = convertComponentInstanceRequirements(component, + componentInstance, component.getComponentInstancesRelations(), nodeTemplate, + originComponentRes.left().value(), componentCache); + if (requirements.isRight()) { + convertNodeTemplatesRes = Either.right(requirements.right().value()); + break; + } + String instanceUniqueId = componentInstance.getUniqueId(); + log.debug("Component instance Requirements converted for instance {}", instanceUniqueId); + + nodeTemplate = requirements.left().value(); + + Component originalComponent = componentCache.get(componentInstance.getActualComponentUid()); + + if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy){ + Component componentOfProxy = componentCache.get(componentInstance.getComponentUid()); + nodeTemplate.setMetadata(convertMetadata(componentOfProxy, true, componentInstance)); + } else { + nodeTemplate.setMetadata(convertMetadata(originalComponent, true, componentInstance)); + } + + Either<ToscaNodeTemplate, ToscaError> capabilities = capabiltyRequirementConvertor + .convertComponentInstanceCapabilties(componentInstance, dataTypes, nodeTemplate); + if (capabilities.isRight()) { + convertNodeTemplatesRes = Either.right(requirements.right().value()); + break; + } + log.debug("Component instance Capabilities converted for instance {}", instanceUniqueId); + + nodeTemplate = capabilities.left().value(); + Map<String, Object> props = new HashMap<>(); + + if (originalComponent.getComponentType() == ComponentTypeEnum.RESOURCE) { + // Adds the properties of parent component to map + addPropertiesOfParentComponent(dataTypes, componentInstance, originalComponent, props); + } + + if (null != componentInstancesProperties && componentInstancesProperties.containsKey(instanceUniqueId)) { + addPropertiesOfComponentInstance(componentInstancesProperties, dataTypes, componentInstance, + instanceUniqueId, props); + } + + if (componentInstancesInputs != null && componentInstancesInputs.containsKey(instanceUniqueId)) { + addComponentInstanceInputs(dataTypes, componentInstancesInputs, componentInstance, instanceUniqueId, + props); + } + if (props != null && !props.isEmpty()) { + nodeTemplate.setProperties(props); + } + + List<GroupInstance> groupInstances = componentInstance.getGroupInstances(); + if (groupInstances != null) { + if (groupsMap == null) { + groupsMap = new HashMap<>(); + } + for (GroupInstance groupInst : groupInstances) { + boolean addToTosca = true; + + List<String> artifacts = groupInst.getArtifacts(); + if (artifacts == null || artifacts.isEmpty()) { + addToTosca = false; + } + + if (addToTosca) { + ToscaGroupTemplate toscaGroup = convertGroupInstance(groupInst); + groupsMap.put(groupInst.getName(), toscaGroup); + } + } + } + + nodeTemplates.put(componentInstance.getName(), nodeTemplate); + } + if (groupsMap != null) { + log.debug("instance groups added"); + topologyTemplate.addGroups(groupsMap); + } + if (component.getComponentType() == ComponentTypeEnum.SERVICE && MapUtils.isNotEmpty(((Service) component).getForwardingPaths())) { + log.debug("Starting converting paths for component {}, name {}", component.getUniqueId(), + component.getName()); + ForwardingPathToscaUtil.addForwardingPaths((Service) component, nodeTemplates, capabiltyRequirementConvertor, componentCache, toscaOperationFacade); + log.debug("Finished converting paths for component {}, name {}", component.getUniqueId(), + component.getName()); + } + if (convertNodeTemplatesRes == null) { + convertNodeTemplatesRes = Either.left(nodeTemplates); + } + log.debug("finish convert topology template for {} for type {}", component.getUniqueId(), + component.getComponentType()); + return convertNodeTemplatesRes; + } + + private void addComponentInstanceInputs(Map<String, DataTypeDefinition> dataTypes, + Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ComponentInstance componentInstance, + String instanceUniqueId, Map<String, Object> props) { + + List<ComponentInstanceInput> instanceInputsList = componentInstancesInputs.get(instanceUniqueId); + if (instanceInputsList != null) { + instanceInputsList.forEach(input -> { + + Supplier<String> supplier = () -> input.getValue() != null && !input.getValue().isEmpty() + ? input.getValue() : input.getDefaultValue(); + convertAndAddValue(dataTypes, componentInstance, props, input, supplier); + }); + } + } + + private void addPropertiesOfComponentInstance( + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties, + Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, String instanceUniqueId, + Map<String, Object> props) { + + if (!MapUtils.isEmpty(componentInstancesProperties)) { + componentInstancesProperties.get(instanceUniqueId).stream() + // Collects filtered properties to List + .collect(Collectors.toList()).stream() + // Converts and adds each value to property map + .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, + () -> prop.getValue())); + } + } + + private void addPropertiesOfParentComponent(Map<String, DataTypeDefinition> dataTypes, + ComponentInstance componentInstance, Component componentOfInstance, Map<String, Object> props) { + + List<PropertyDefinition> componentProperties = ((Resource) componentOfInstance).getProperties(); + if (!CollectionUtils.isEmpty(componentProperties)) { + componentProperties.stream() + // Filters out properties with empty default values + .filter(prop -> !StringUtils.isEmpty(prop.getDefaultValue())) + // Collects filtered properties to List + .collect(Collectors.toList()).stream() + // Converts and adds each value to property map + .forEach(prop -> convertAndAddValue(dataTypes, componentInstance, props, prop, + () -> prop.getDefaultValue())); + } + } + + /** + * @param dataTypes + * @param componentInstance + * @param props + * @param prop + * @param supplier + */ + private void convertAndAddValue(Map<String, DataTypeDefinition> dataTypes, ComponentInstance componentInstance, + Map<String, Object> props, PropertyDefinition prop, Supplier<String> supplier) { + Object convertedValue = convertValue(dataTypes, componentInstance, prop, supplier); + if (!ToscaValueBaseConverter.isEmptyObjectValue(convertedValue)) { + props.put(prop.getName(), convertedValue); + } + } + + private <T extends PropertyDefinition> Object convertValue(Map<String, DataTypeDefinition> dataTypes, + ComponentInstance componentInstance, T input, Supplier<String> supplier) { + log.debug("Convert property or input value {} for instance {}", input.getName(), + componentInstance.getUniqueId()); + String propertyType = input.getType(); + String innerType = null; + if (input.getSchema() != null && input.getSchema().getProperty() != null) { + innerType = input.getSchema().getProperty().getType(); + } + return propertyConvertor.convertToToscaObject(propertyType, supplier.get(), innerType, dataTypes); + } + + private ToscaGroupTemplate convertGroup(GroupDefinition group) { + ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); + Map<String, String> members = group.getMembers(); + if (members != null) + toscaGroup.setMembers(new ArrayList<String>(members.keySet())); + + Supplier<String> supplGroupType = () -> group.getType(); + Supplier<String> supplDescription = () -> group.getDescription(); + Supplier<List<? extends GroupProperty>> supplProperties = () -> group.convertToGroupProperties(); + Supplier<String> supplgroupName = () -> group.getName(); + Supplier<String> supplInvariantUUID = () -> group.getInvariantUUID(); + Supplier<String> supplGroupUUID = () -> group.getGroupUUID(); + Supplier<String> supplVersion = () -> group.getVersion(); + + IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, + supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); + toscaGroup.setMetadata(toscaMetadata); + return toscaGroup; + } + + private ToscaGroupTemplate convertGroupInstance(GroupInstance groupInstance) { + ToscaGroupTemplate toscaGroup = new ToscaGroupTemplate(); + + Supplier<String> supplGroupType = () -> groupInstance.getType(); + Supplier<String> supplDescription = () -> groupInstance.getDescription(); + Supplier<List<? extends GroupProperty>> supplProperties = () -> groupInstance + .convertToGroupInstancesProperties(); + Supplier<String> supplgroupName = () -> groupInstance.getGroupName(); + Supplier<String> supplInvariantUUID = () -> groupInstance.getInvariantUUID(); + Supplier<String> supplGroupUUID = () -> groupInstance.getGroupUUID(); + Supplier<String> supplVersion = () -> groupInstance.getVersion(); + + IToscaMetadata toscaMetadata = fillGroup(toscaGroup, supplProperties, supplDescription, supplgroupName, + supplInvariantUUID, supplGroupUUID, supplVersion, supplGroupType); + + toscaMetadata.setCustomizationUUID(groupInstance.getCustomizationUUID()); + toscaGroup.setMetadata(toscaMetadata); + return toscaGroup; + } + + private IToscaMetadata fillGroup(ToscaGroupTemplate toscaGroup, Supplier<List<? extends GroupProperty>> props, + Supplier<String> description, Supplier<String> groupName, Supplier<String> invariantUUID, + Supplier<String> groupUUID, Supplier<String> version, Supplier<String> groupType) { + boolean isVfModule = groupType.get().equals(Constants.DEFAULT_GROUP_VF_MODULE) ? true : false; + toscaGroup.setType(groupType.get()); + + IToscaMetadata toscaMetadata; + if (!isVfModule) { + toscaMetadata = new ToscaMetadata(); + } else { + toscaMetadata = new VfModuleToscaMetadata(); + + Map<String, Object> properties = fillGroupProperties(props.get()); + if (!properties.containsKey(VF_MODULE_DESC_KEY) + || StringUtils.isEmpty((String) properties.get(VF_MODULE_DESC_KEY))) { + properties.put(VF_MODULE_DESC_KEY, description.get()); + } + toscaGroup.setProperties(properties); + } + toscaMetadata.setName(groupName.get()); + toscaMetadata.setInvariantUUID(invariantUUID.get()); + toscaMetadata.setUUID(groupUUID.get()); + toscaMetadata.setVersion(version.get()); + return toscaMetadata; + } + + private Map<String, Object> fillGroupProperties(List<? extends GroupProperty> groupProps) { + Map<String, Object> properties = new HashMap<>(); + if (groupProps != null) { + for (GroupProperty gp : groupProps) { + if (gp.getName().equals(Constants.IS_BASE)) { + Boolean isBase = Boolean.parseBoolean(gp.getValue()); + String type = isBase ? VF_MODULE_TYPE_BASE : VF_MODULE_TYPE_EXPANSION; + properties.put(VF_MODULE_TYPE_KEY, type); + } else { + Object value = null; + String type = gp.getType(); + + switch (type) { + case "integer": + if (gp.getValue() != null) { + value = Integer.valueOf(gp.getValue()); + } + break; + case "boolean": + if (gp.getValue() != null) { + value = Boolean.valueOf(gp.getValue()); + } + break; + + default: + value = gp.getValue(); + break; + } + properties.put(gp.getName(), value); + } + } + } + return properties; + } + + private ToscaNodeType createNodeType(Component component) { + ToscaNodeType toscaNodeType = new ToscaNodeType(); + if (ModelConverter.isAtomicComponent(component)) { + if (((Resource) component).getDerivedFrom() != null) { + toscaNodeType.setDerived_from(((Resource) component).getDerivedFrom().get(0)); + } + toscaNodeType.setDescription(component.getDescription()); // or + // name?? + } else { + String derivedFrom = null != component.getDerivedFromGenericType() ? component.getDerivedFromGenericType() + : "tosca.nodes.Root"; + toscaNodeType.setDerived_from(derivedFrom); + } + return toscaNodeType; + } + + private Either<Map<String, ToscaNodeType>, ToscaError> createProxyNodeTypes(Map<String, Component> componentCache ,Component container ) { + + Map<String, ToscaNodeType> nodeTypesMap = null; + Either<Map<String, ToscaNodeType>, ToscaError> res = Either.left(nodeTypesMap); + + List<ComponentInstance> componetInstances = container.getComponentInstances(); + + if (componetInstances == null || componetInstances.isEmpty()) + return res; + Map<String, ComponentInstance> serviceProxyInstanceList = new HashMap<>(); + List<ComponentInstance> proxyInst = componetInstances.stream() + .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceProxy.name())) + .collect(Collectors.toList()); + if (proxyInst != null && !proxyInst.isEmpty()) { + for (ComponentInstance inst : proxyInst) { + serviceProxyInstanceList.put(inst.getToscaComponentName(), inst); + } + } + + if (serviceProxyInstanceList.isEmpty()) + return res; + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreCapabilities(false); + filter.setIgnoreComponentInstances(false); + Either<Resource, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade + .getLatestByName("serviceProxy"); + if (serviceProxyOrigin.isRight()) { + log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", + serviceProxyOrigin.right().value()); + return Either.right(ToscaError.NOT_SUPPORTED_TOSCA_TYPE); + } + Component origComponent = serviceProxyOrigin.left().value(); + + nodeTypesMap = new HashMap<>(); + for (Entry<String, ComponentInstance> entryProxy : serviceProxyInstanceList.entrySet()) { + Component serviceComponent = null; + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreCategories(false); + Either<Component, StorageOperationStatus> service = toscaOperationFacade + .getToscaElement(entryProxy.getValue().getSourceModelUid(), componentParametersView); + if (service.isRight()) { + log.debug("Failed to fetch resource with id {} for instance {}"); + } else + serviceComponent = service.left().value(); + + ToscaNodeType toscaNodeType = createProxyNodeType(componentCache , origComponent, serviceComponent, entryProxy.getValue()); + nodeTypesMap.put(entryProxy.getKey(), toscaNodeType); + } + + return Either.left(nodeTypesMap); + } + + private ToscaNodeType createProxyNodeType(Map<String, Component> componentCache , Component origComponent, Component proxyComponent, + ComponentInstance instance) { + ToscaNodeType toscaNodeType = new ToscaNodeType(); + String derivedFrom = ((Resource) origComponent).getToscaResourceName(); + + toscaNodeType.setDerived_from(derivedFrom); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); + if (dataTypesEither.isRight()) { + log.debug("Failed to retrieve all data types {}", dataTypesEither.right().value()); + } + Map<String, DataTypeDefinition> dataTypes = dataTypesEither.left().value(); + Map<String, ToscaCapability> capabilities = this.capabiltyRequirementConvertor + .convertProxyCapabilities( componentCache ,origComponent, proxyComponent, instance, dataTypes); + + toscaNodeType.setCapabilities(capabilities); + + return toscaNodeType; + } + + private Either<ToscaNodeTemplate, ToscaError> convertComponentInstanceRequirements(Component component, + ComponentInstance componentInstance, List<RequirementCapabilityRelDef> relations, + ToscaNodeTemplate nodeTypeTemplate, Component originComponent, Map<String, Component> componentCache) { + + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + if (!addRequirements(component, componentInstance, relations, originComponent, toscaRequirements, componentCache)) { + log.debug("Failed to convert component instance requirements for the component instance {}. ", + componentInstance.getName()); + return Either.right(ToscaError.NODE_TYPE_REQUIREMENT_ERROR); + } + if (!toscaRequirements.isEmpty()) { + nodeTypeTemplate.setRequirements(toscaRequirements); + } + log.debug("Finished to convert requirements for the node type {} ", componentInstance.getName()); + return Either.left(nodeTypeTemplate); + } + + private boolean addRequirements(Component component, ComponentInstance componentInstance, + List<RequirementCapabilityRelDef> relations, Component originComponent, + List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) { + boolean result; + List<RequirementCapabilityRelDef> filteredRelations = relations.stream() + .filter(p -> componentInstance.getUniqueId().equals(p.getFromNode())).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(filteredRelations)) { + result = true; + } else { + result = !filteredRelations.stream().filter(rel -> !addRequirement(componentInstance, originComponent, + component.getComponentInstances(), rel, toscaRequirements, componentCache)).findFirst().isPresent(); + } + return result; + } + + private boolean addRequirement(ComponentInstance fromInstance, Component fromOriginComponent, + List<ComponentInstance> instancesList, RequirementCapabilityRelDef rel, + List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Map<String, Component> componentCache) { + + boolean result = true; + Map<String, List<RequirementDefinition>> reqMap = fromOriginComponent.getRequirements(); + RelationshipInfo reqAndRelationshipPair = rel.getRelationships().get(0).getRelation(); + Either<Component, StorageOperationStatus> getOriginRes = null; + Optional<RequirementDefinition> reqOpt = null; + Component toOriginComponent = null; + Optional<CapabilityDefinition> cap = null; + + ComponentInstance toInstance = instancesList.stream().filter(i -> rel.getToNode().equals(i.getUniqueId())) + .findFirst().orElse(null); + if (toInstance == null) { + log.debug("Failed to find a relation from the node {} to the node {}", fromInstance.getName(), + rel.getToNode()); + result = false; + } + if (result) { + reqOpt = findRequirement(fromOriginComponent, reqMap, reqAndRelationshipPair, fromInstance.getUniqueId()); + if (!reqOpt.isPresent()) { + log.debug("Failed to find a requirement with uniqueId {} on a component with uniqueId {}", + reqAndRelationshipPair.getRequirementUid(), fromOriginComponent.getUniqueId()); + result = false; + } + } + if (result) { + ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreComponentInstances(false); + filter.setIgnoreCapabilities(false); + getOriginRes = toscaOperationFacade.getToscaElement(toInstance.getActualComponentUid(), filter); + if (getOriginRes.isRight()) { + log.debug("Failed to build substituted name for the requirement {}. Failed to get an origin component with uniqueId {}", + reqOpt.get().getName(), toInstance.getActualComponentUid()); + result = false; + } + } + if (result) { + toOriginComponent = getOriginRes.left().value(); + cap = toOriginComponent.getCapabilities().get(reqOpt.get().getCapability()).stream() + .filter(c -> isCapabilityBelongToRelation(reqAndRelationshipPair, c)).findFirst(); + if (!cap.isPresent()) { + cap = findCapability(reqAndRelationshipPair, toOriginComponent, fromOriginComponent, reqOpt.get(), fromInstance); + if(!cap.isPresent()){ + result = false; + log.debug("Failed to find a capability with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + } + } + } + if (result) { + result = buildAndAddRequirement(toscaRequirements, fromOriginComponent, toOriginComponent, cap.get(), + reqOpt.get(), reqAndRelationshipPair, toInstance, componentCache); + } + return result; + } + + private boolean isCapabilityBelongToRelation(RelationshipInfo reqAndRelationshipPair, CapabilityDefinition capability) { + return capability.getName().equals(reqAndRelationshipPair.getCapability()) && (capability.getOwnerId() !=null && capability.getOwnerId().equals(reqAndRelationshipPair.getCapabilityOwnerId())); + } + + private Optional<CapabilityDefinition> findCapability(RelationshipInfo reqAndRelationshipPair, Component toOriginComponent, Component fromOriginComponent, RequirementDefinition requirement, ComponentInstance fromInstance) { + Optional<CapabilityDefinition> cap = toOriginComponent.getCapabilities().get(requirement.getCapability()).stream().filter(c -> c.getType().equals(requirement.getCapability())).findFirst(); + if (!cap.isPresent()) { + log.debug("Failed to find a capability with name {} on a component with uniqueId {}", reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + } + return cap; + } + + private boolean buildAndAddRequirement(List<Map<String, ToscaTemplateRequirement>> toscaRequirements, Component fromOriginComponent, Component toOriginComponent, CapabilityDefinition capability, RequirementDefinition requirement, RelationshipInfo reqAndRelationshipPair, ComponentInstance toInstance, Map<String, Component> componentCache) { + boolean result = true; + Either<String, Boolean> buildReqNameRes = null; + List<String> reducedPath = capability.getPath(); + if(capability.getOwnerId() !=null){ + reducedPath = capabiltyRequirementConvertor.getReducedPathByOwner(capability.getPath() , capability.getOwnerId() ); + } + Either<String, Boolean> buildCapNameRes = capabiltyRequirementConvertor.buildSubstitutedName(componentCache, + toOriginComponent, reducedPath, reqAndRelationshipPair.getCapability()); + if (buildCapNameRes.isRight()) { + log.debug( + "Failed to build a substituted capability name for the capability with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getCapability(), fromOriginComponent.getUniqueId()); + result = false; + } + if (result) { + buildReqNameRes = capabiltyRequirementConvertor.buildSubstitutedName(componentCache, fromOriginComponent, + requirement.getPath(), reqAndRelationshipPair.getRequirement()); + if (buildReqNameRes.isRight()) { + log.debug( + "Failed to build a substituted requirement name for the requirement with name {} on a component with uniqueId {}", + reqAndRelationshipPair.getRequirement(), fromOriginComponent.getUniqueId()); + result = false; + } + } + if (result) { + ToscaTemplateRequirement toscaRequirement = new ToscaTemplateRequirement(); + Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>(); + toscaRequirement.setNode(toInstance.getName()); + toscaRequirement.setCapability(buildCapNameRes.left().value()); + toscaReqMap.put(buildReqNameRes.left().value(), toscaRequirement); + toscaRequirements.add(toscaReqMap); + } + return result; + } + + private Optional<RequirementDefinition> findRequirement(Component fromOriginComponent, Map<String, List<RequirementDefinition>> reqMap, RelationshipInfo reqAndRelationshipPair, String fromInstanceId) { + for(List<RequirementDefinition> reqList: reqMap.values()){ + Optional<RequirementDefinition> reqOpt = reqList.stream().filter(r -> isRequirementBelongToRelation(fromOriginComponent, reqAndRelationshipPair, r, fromInstanceId)).findFirst(); + if(reqOpt.isPresent()){ + return reqOpt; + } + } + return Optional.empty(); + } + + /** + * Allows detecting the requirement belonging to the received relationship + * The detection logic is: A requirement belongs to a relationship IF 1.The + * name of the requirement equals to the "requirement" field of the + * relation; AND 2. In case of a non-atomic resource, OwnerId of the + * requirement equals to requirementOwnerId of the relation OR uniqueId of + * toInstance equals to capabilityOwnerId of the relation + */ + private boolean isRequirementBelongToRelation(Component originComponent, RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId) { + if (!StringUtils.equals(requirement.getName(), reqAndRelationshipPair.getRequirement())){ + log.debug("Failed to find a requirement with name {} and reqAndRelationshipPair {}", + requirement.getName(), reqAndRelationshipPair.getRequirement()); + return false; + } + if (!ModelConverter.isAtomicComponent(originComponent)) + return isRequirementBelongToOwner(reqAndRelationshipPair, requirement, fromInstanceId, originComponent); + return true; + } + + private boolean isRequirementBelongToOwner(RelationshipInfo reqAndRelationshipPair, RequirementDefinition requirement, String fromInstanceId, Component originComponent) { + return StringUtils.equals(requirement.getOwnerId(), reqAndRelationshipPair.getRequirementOwnerId()) || (isCvfc(originComponent) && StringUtils.equals(fromInstanceId, reqAndRelationshipPair.getRequirementOwnerId())); + } + + private boolean isCvfc(Component component) { + if (component.getComponentType() != ComponentTypeEnum.RESOURCE) + return false; + return ((Resource) component).getResourceType() == ResourceTypeEnum.CVFC; + } + + private Either<SubstitutionMapping, ToscaError> convertCapabilities(Component component, + SubstitutionMapping substitutionMappings, Map<String, Component> componentCache) { + + Either<SubstitutionMapping, ToscaError> result = Either.left(substitutionMappings); + Either<Map<String, String[]>, ToscaError> toscaCapabilitiesRes = capabiltyRequirementConvertor + .convertSubstitutionMappingCapabilities(componentCache, component); + if (toscaCapabilitiesRes.isRight()) { + result = Either.right(toscaCapabilitiesRes.right().value()); + log.error("Failed convert capabilities for the component {}. ", component.getName()); + } else if (MapUtils.isNotEmpty(toscaCapabilitiesRes.left().value())) { + substitutionMappings.setCapabilities(toscaCapabilitiesRes.left().value()); + log.debug("Finish convert capabilities for the component {}. ", component.getName()); + } + log.debug("Finished to convert capabilities for the component {}. ", component.getName()); + return result; + } + + private Either<ToscaNodeType, ToscaError> convertCapabilities(Component component, ToscaNodeType nodeType, + Map<String, DataTypeDefinition> dataTypes) { + Map<String, ToscaCapability> toscaCapabilities = capabiltyRequirementConvertor.convertCapabilities(component, + dataTypes); + if (!toscaCapabilities.isEmpty()) { + nodeType.setCapabilities(toscaCapabilities); + } + log.debug("Finish convert Capabilities for node type"); + + return Either.left(nodeType); + } + + private static class CustomRepresenter extends Representer { + public CustomRepresenter() { + super(); + // null representer is exceptional and it is stored as an instance + // variable. + this.nullRepresenter = new RepresentNull(); + + } + + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, + Tag customTag) { + if (propertyValue == null) { + return null; + } else { + // skip not relevant for Tosca property + if ("dependencies".equals(property.getName())) { + return null; + } + NodeTuple defaultNode = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + + return "_defaultp_".equals(property.getName()) + ? new NodeTuple(representData("default"), defaultNode.getValueNode()) : defaultNode; + } + } + + @Override + protected MappingNode representJavaBean(Set<Property> properties, Object javaBean) { + // remove the bean type from the output yaml (!! ...) + if (!classTags.containsKey(javaBean.getClass())) + addClassTag(javaBean.getClass(), Tag.MAP); + + return super.representJavaBean(properties, javaBean); + } + + private class RepresentNull implements Represent { + @Override + public Node representData(Object data) { + // possible values are here http://yaml.org/type/null.html + return representScalar(Tag.NULL, ""); + } + } + } + + private static class UnsortedPropertyUtils extends PropertyUtils { + @Override + protected Set<Property> createPropertySet(Class<? extends Object> type, BeanAccess bAccess) + throws IntrospectionException { + Collection<Property> fields = getPropertiesMap(type, BeanAccess.FIELD).values(); + return new LinkedHashSet<>(fields); + } + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java index 6b1895b6ec..49fd91cfed 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaRepresentation.java @@ -20,30 +20,30 @@ package org.openecomp.sdc.be.tosca; -import java.util.List; - import org.apache.commons.lang3.tuple.Triple; import org.openecomp.sdc.be.model.Component; +import java.util.List; + public class ToscaRepresentation { - private String mainYaml; - private List<Triple<String, String, Component>> dependencies; + private String mainYaml; + private List<Triple<String, String, Component>> dependencies; - public String getMainYaml() { - return mainYaml; - } + public String getMainYaml() { + return mainYaml; + } - public void setMainYaml(String mainYaml) { - this.mainYaml = mainYaml; - } + public void setMainYaml(String mainYaml) { + this.mainYaml = mainYaml; + } - public List<Triple<String, String, Component>> getDependencies() { - return dependencies; - } + public List<Triple<String, String, Component>> getDependencies() { + return dependencies; + } - public void setDependencies(List<Triple<String, String, Component>> dependancies) { - this.dependencies = dependancies; - } + public void setDependencies(List<Triple<String, String, Component>> dependancies) { + this.dependencies = dependancies; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java index 0c54e7229e..8abaaf73f8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaUtils.java @@ -20,92 +20,88 @@ package org.openecomp.sdc.be.tosca; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.Component; +import java.lang.reflect.Field; +import java.util.*; + public class ToscaUtils { - public static boolean isComplexVfc(Component component) { - if (ComponentTypeEnum.RESOURCE == component.getComponentType()) { - ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); - if (ResourceTypeEnum.CVFC == resourceType) { - return true; - } - } - return false; - } - - public static Map<String, Object> objectToMap(Object objectToConvert, Class<?> clazz) throws IllegalArgumentException, IllegalAccessException { - Map<String, Object> map = new HashMap<>(); - List<Field> fields = new ArrayList<>(); - - fields = getAllFields(fields, clazz); - - for (Field field : fields) { - field.setAccessible(true); - map.put(field.getName(), field.get(objectToConvert)); - } - return map; - } - - public static List<Field> getAllFields(List<Field> fields, Class<?> type) { - fields.addAll(Arrays.asList(type.getDeclaredFields())); - - if (type.getSuperclass() != null) { - fields = getAllFields(fields, type.getSuperclass()); - } - return fields; - } - - public static class SubstituitionEntry{ - - private String fullName = ""; - private String sourceName = ""; - private String owner = ""; - - public SubstituitionEntry() {} - - public SubstituitionEntry(String fullName, String sourceName, String owner) { - if(fullName != null) - this.fullName = fullName; - if(sourceName != null) - this.sourceName = sourceName; - if(owner != null) - this.owner = owner; - } - - public String getFullName() { - return fullName; - } - - public void setFullName(String fullName) { - this.fullName = fullName; - } - - public String getSourceName() { - return sourceName; - } - - public void setSourceName(String sourceName) { - this.sourceName = sourceName; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - } - + public static boolean isComplexVfc(Component component) { + if (ComponentTypeEnum.RESOURCE == component.getComponentType()) { + ResourceTypeEnum resourceType = ((ResourceMetadataDataDefinition) component.getComponentMetadataDefinition().getMetadataDataDefinition()).getResourceType(); + if (ResourceTypeEnum.CVFC == resourceType) { + return true; + } + } + return false; + } + + public static Map<String, Object> objectToMap(Object objectToConvert, Class<?> clazz) throws IllegalArgumentException, IllegalAccessException { + Map<String, Object> map = new HashMap<>(); + List<Field> fields = new ArrayList<>(); + + fields = getAllFields(fields, clazz); + + for (Field field : fields) { + field.setAccessible(true); + map.put(field.getName(), field.get(objectToConvert)); + } + return map; + } + + public static List<Field> getAllFields(List<Field> fields, Class<?> type) { + fields.addAll(Arrays.asList(type.getDeclaredFields())); + + if (type.getSuperclass() != null) { + fields = getAllFields(fields, type.getSuperclass()); + } + return fields; + } + + public static class SubstituitionEntry{ + + private String fullName = ""; + private String sourceName = ""; + private String owner = ""; + + public SubstituitionEntry() {} + + public SubstituitionEntry(String fullName, String sourceName, String owner) { + if(fullName != null) + this.fullName = fullName; + if(sourceName != null) + this.sourceName = sourceName; + if(owner != null) + this.owner = owner; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getSourceName() { + return sourceName; + } + + public void setSourceName(String sourceName) { + this.sourceName = sourceName; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java index 0c586c7043..f1a7dcb9e5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/EntrySchema.java @@ -21,23 +21,23 @@ package org.openecomp.sdc.be.tosca.model; public class EntrySchema { - private String type; - private String description; + private String type; + private String description; - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java index 70b05b8158..1bb865f562 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/IToscaMetadata.java @@ -22,13 +22,13 @@ package org.openecomp.sdc.be.tosca.model; public interface IToscaMetadata { - public void setName(String name); + public void setName(String name); - public void setInvariantUUID(String invariantUUID); + public void setInvariantUUID(String invariantUUID); - public void setUUID(String uUID); + public void setUUID(String uUID); - public void setVersion(String version); - - public void setCustomizationUUID(String customizationUUID); + public void setVersion(String version); + + public void setCustomizationUUID(String customizationUUID); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java index 5dc8ddee2a..bbbb303900 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/SubstitutionMapping.java @@ -23,36 +23,36 @@ package org.openecomp.sdc.be.tosca.model; import java.util.Map; public class SubstitutionMapping { - private String node_type; - private Map<String, String[]> capabilities; - private Map<String, String[]> requirements; - - public SubstitutionMapping() { - super(); - // TODO Auto-generated constructor stub - } - - public String getNode_type() { - return node_type; - } - - public void setNode_type(String node_type) { - this.node_type = node_type; - } - - public Map<String, String[]> getCapabilities() { - return capabilities; - } - - public void setCapabilities(Map<String, String[]> capabilities) { - this.capabilities = capabilities; - } - - public Map<String, String[]> getRequirements() { - return requirements; - } - - public void setRequirements(Map<String, String[]> requirements) { - this.requirements = requirements; - } + private String node_type; + private Map<String, String[]> capabilities; + private Map<String, String[]> requirements; + + public SubstitutionMapping() { + super(); + // TODO Auto-generated constructor stub + } + + public String getNode_type() { + return node_type; + } + + public void setNode_type(String node_type) { + this.node_type = node_type; + } + + public Map<String, String[]> getCapabilities() { + return capabilities; + } + + public void setCapabilities(Map<String, String[]> capabilities) { + this.capabilities = capabilities; + } + + public Map<String, String[]> getRequirements() { + return requirements; + } + + public void setRequirements(Map<String, String[]> requirements) { + this.requirements = requirements; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java index 2688e5e6b3..d26fd0447c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaCapability.java @@ -25,56 +25,56 @@ import java.util.Map; public class ToscaCapability { - private String type; - private String description; + private String type; + private String description; - private List<Object> occurrences; + private List<Object> occurrences; - private List<String> valid_source_types; + private List<String> valid_source_types; - private Map<String, ToscaProperty> properties; + private Map<String, ToscaProperty> properties; - public List<String> getValid_source_types() { - return valid_source_types; - } + public List<String> getValid_source_types() { + return valid_source_types; + } - public void setValid_source_types(List<String> valid_source_types) { - this.valid_source_types = valid_source_types; - } + public void setValid_source_types(List<String> valid_source_types) { + this.valid_source_types = valid_source_types; + } - public ToscaCapability() { - } + public ToscaCapability() { + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public List<Object> getOccurrences() { - return occurrences; - } + public List<Object> getOccurrences() { + return occurrences; + } - public void setOccurrences(List<Object> occurrences) { - this.occurrences = occurrences; - } + public void setOccurrences(List<Object> occurrences) { + this.occurrences = occurrences; + } - public Map<String, ToscaProperty> getProperties() { - return properties; - } + public Map<String, ToscaProperty> getProperties() { + return properties; + } - public void setProperties(Map<String, ToscaProperty> properties) { - this.properties = properties; - } + public void setProperties(Map<String, ToscaProperty> properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java index b91cffa5be..2c5e095b8f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaGroupTemplate.java @@ -24,46 +24,46 @@ import java.util.List; import java.util.Map; public class ToscaGroupTemplate { - private String type; - List<String> members; - private IToscaMetadata metadata; - private Map<String, Object> properties; + private String type; + List<String> members; + private IToscaMetadata metadata; + private Map<String, Object> properties; - public ToscaGroupTemplate() { - super(); + public ToscaGroupTemplate() { + super(); - } + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public List<String> getMembers() { - return members; - } + public List<String> getMembers() { + return members; + } - public void setMembers(List<String> members) { - this.members = members; - } + public void setMembers(List<String> members) { + this.members = members; + } - public IToscaMetadata getMetadata() { - return metadata; - } + public IToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(IToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(IToscaMetadata metadata) { + this.metadata = metadata; + } - public Map<String, Object> getProperties() { - return properties; - } + public Map<String, Object> getProperties() { + return properties; + } - public void setProperties(Map<String, Object> properties) { - this.properties = properties; - } + public void setProperties(Map<String, Object> properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java index 4f91e211cc..69907beaec 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaMetadata.java @@ -21,200 +21,200 @@ package org.openecomp.sdc.be.tosca.model; public class ToscaMetadata implements IToscaMetadata { - private String invariantUUID; - private String UUID; - private String customizationUUID; - private String version; - private String name; - private String description; - private String type; - private String category; - private String subcategory; - private String resourceVendor; - private String resourceVendorRelease; - private String resourceVendorModelNumber; - private String serviceType; - private String serviceRole; - private Boolean serviceEcompNaming; - private Boolean ecompGeneratedNaming; - private String namingPolicy; - private String sourceModelInvariant; - private String environmentContext; - private String sourceModelName; - private String sourceModelUuid; - - - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getInvariantUUID() { - return invariantUUID; - } - - @Override - public void setInvariantUUID(String invariantUUID) { - this.invariantUUID = invariantUUID; - } - - public String getUUID() { - return UUID; - } - - @Override - public void setUUID(String uUID) { - UUID = uUID; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getCategory() { - return category; - } - - public void setCategory(String category) { - this.category = category; - } - - public String getSubcategory() { - return subcategory; - } - - public void setSubcategory(String subcategory) { - this.subcategory = subcategory; - } - - public String getResourceVendor() { - return resourceVendor; - } - - public void setResourceVendor(String resourceVendor) { - this.resourceVendor = resourceVendor; - } - - public String getResourceVendorRelease() { - return resourceVendorRelease; - } - - public void setResourceVendorRelease(String resourceVendorRelease) { - this.resourceVendorRelease = resourceVendorRelease; - } - - public String getResourceVendorModelNumber() { - return resourceVendorModelNumber; - } - - public void setResourceVendorModelNumber(String resourceVendorModelNumber) { - this.resourceVendorModelNumber = resourceVendorModelNumber; - } - - public String getServiceType() { - return serviceType; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - - public String getServiceRole() { - return serviceRole; - } - - public void setServiceRole(String serviceRole) { - this.serviceRole = serviceRole; - } - - public Boolean isEcompGeneratedNaming() { - return ecompGeneratedNaming; - } - - public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { - this.ecompGeneratedNaming = ecompGeneratedNaming; - } - - public String isNamingPolicy() { - return namingPolicy; - } - - public void setNamingPolicy(String namingPolicy) { - this.namingPolicy = namingPolicy; - } - - public Boolean getServiceEcompNaming() { - return serviceEcompNaming; - } - - public void setServiceEcompNaming(Boolean serviceEcompNaming) { - this.serviceEcompNaming = serviceEcompNaming; - } - - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - public String getCustomizationUUID() { - return customizationUUID; - } - - public void setCustomizationUUID(String customizationUUID) { - this.customizationUUID = customizationUUID; - } - - public String getSourceModelInvariant() { - return sourceModelInvariant; - } - - public void setSourceModelInvariant(String sourceModelInvariant) { - this.sourceModelInvariant = sourceModelInvariant; - } - - public String getSourceModelName() { - return sourceModelName; - } - - public void setSourceModelName(String sourceModelName) { - this.sourceModelName = sourceModelName; - } - - public String getSourceModelUuid() { - return sourceModelUuid; - } - - public void setSourceModelUuid(String sourceModelUuid) { - this.sourceModelUuid = sourceModelUuid; - } - - - - public String getEnvironmentContext() { - return environmentContext; - } - - public void setEnvironmentContext(String environmentContext) { - this.environmentContext = environmentContext; - } + private String invariantUUID; + private String UUID; + private String customizationUUID; + private String version; + private String name; + private String description; + private String type; + private String category; + private String subcategory; + private String resourceVendor; + private String resourceVendorRelease; + private String resourceVendorModelNumber; + private String serviceType; + private String serviceRole; + private Boolean serviceEcompNaming; + private Boolean ecompGeneratedNaming; + private String namingPolicy; + private String sourceModelInvariant; + private String environmentContext; + private String sourceModelName; + private String sourceModelUuid; + + + public String getName() { + return name; + } + + @Override + public void setName(String name) { + this.name = name; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + @Override + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public String getUUID() { + return UUID; + } + + @Override + public void setUUID(String uUID) { + UUID = uUID; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } + + public String getResourceVendor() { + return resourceVendor; + } + + public void setResourceVendor(String resourceVendor) { + this.resourceVendor = resourceVendor; + } + + public String getResourceVendorRelease() { + return resourceVendorRelease; + } + + public void setResourceVendorRelease(String resourceVendorRelease) { + this.resourceVendorRelease = resourceVendorRelease; + } + + public String getResourceVendorModelNumber() { + return resourceVendorModelNumber; + } + + public void setResourceVendorModelNumber(String resourceVendorModelNumber) { + this.resourceVendorModelNumber = resourceVendorModelNumber; + } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public Boolean isEcompGeneratedNaming() { + return ecompGeneratedNaming; + } + + public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { + this.ecompGeneratedNaming = ecompGeneratedNaming; + } + + public String isNamingPolicy() { + return namingPolicy; + } + + public void setNamingPolicy(String namingPolicy) { + this.namingPolicy = namingPolicy; + } + + public Boolean getServiceEcompNaming() { + return serviceEcompNaming; + } + + public void setServiceEcompNaming(Boolean serviceEcompNaming) { + this.serviceEcompNaming = serviceEcompNaming; + } + + public String getVersion() { + return version; + } + + @Override + public void setVersion(String version) { + this.version = version; + } + + public String getCustomizationUUID() { + return customizationUUID; + } + + public void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + + public String getSourceModelInvariant() { + return sourceModelInvariant; + } + + public void setSourceModelInvariant(String sourceModelInvariant) { + this.sourceModelInvariant = sourceModelInvariant; + } + + public String getSourceModelName() { + return sourceModelName; + } + + public void setSourceModelName(String sourceModelName) { + this.sourceModelName = sourceModelName; + } + + public String getSourceModelUuid() { + return sourceModelUuid; + } + + public void setSourceModelUuid(String sourceModelUuid) { + this.sourceModelUuid = sourceModelUuid; + } + + + + public String getEnvironmentContext() { + return environmentContext; + } + + public void setEnvironmentContext(String environmentContext) { + this.environmentContext = environmentContext; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java index b2d7ef5ab6..c27944e8ee 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java @@ -24,50 +24,58 @@ import java.util.List; import java.util.Map; public class ToscaNodeTemplate { - private String type; - private ToscaMetadata metadata; - private Map<String, Object> properties; - private List<Map<String, ToscaTemplateRequirement>> requirements; - private Map<String, ToscaTemplateCapability> capabilities; + private String type; + private ToscaMetadata metadata; + private String description; + private Map<String, Object> properties; + private List<Map<String, ToscaTemplateRequirement>> requirements; + private Map<String, ToscaTemplateCapability> capabilities; - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public Map<String, Object> getProperties() { - return properties; - } + public Map<String, Object> getProperties() { + return properties; + } - public void setProperties(Map<String, Object> properties) { - this.properties = properties; - } + public void setProperties(Map<String, Object> properties) { + this.properties = properties; + } - public List<Map<String, ToscaTemplateRequirement>> getRequirements() { - return requirements; - } + public List<Map<String, ToscaTemplateRequirement>> getRequirements() { + return requirements; + } - public void setRequirements(List<Map<String, ToscaTemplateRequirement>> requirements) { - this.requirements = requirements; - } + public void setRequirements(List<Map<String, ToscaTemplateRequirement>> requirements) { + this.requirements = requirements; + } - public Map<String, ToscaTemplateCapability> getCapabilities() { - return capabilities; - } + public Map<String, ToscaTemplateCapability> getCapabilities() { + return capabilities; + } - public void setCapabilities(Map<String, ToscaTemplateCapability> capabilities) { - this.capabilities = capabilities; - } + public void setCapabilities(Map<String, ToscaTemplateCapability> capabilities) { + this.capabilities = capabilities; + } - public ToscaMetadata getMetadata() { - return metadata; - } + public ToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(ToscaMetadata metadata) { + this.metadata = metadata; + } + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java index df9070f49c..4f56cc3bef 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java @@ -24,64 +24,64 @@ import java.util.List; import java.util.Map; public class ToscaNodeType { - public ToscaNodeType() { - } + public ToscaNodeType() { + } - private ToscaMetadata metadata; - private String derived_from; - private String description; + private ToscaMetadata metadata; + private String derived_from; + private String description; - private Map<String, ToscaProperty> properties; - private Map<String, ToscaCapability> capabilities; + private Map<String, ToscaProperty> properties; + private Map<String, ToscaCapability> capabilities; - private List<Map<String, ToscaRequirement>> requirements; + private List<Map<String, ToscaRequirement>> requirements; - public Map<String, ToscaProperty> getProperties() { - return properties; - } + public Map<String, ToscaProperty> getProperties() { + return properties; + } - public void setProperties(Map<String, ToscaProperty> properties) { - this.properties = properties; - } + public void setProperties(Map<String, ToscaProperty> properties) { + this.properties = properties; + } - public Map<String, ToscaCapability> getCapabilities() { - return capabilities; - } + public Map<String, ToscaCapability> getCapabilities() { + return capabilities; + } - public void setCapabilities(Map<String, ToscaCapability> capabilities) { - this.capabilities = capabilities; - } + public void setCapabilities(Map<String, ToscaCapability> capabilities) { + this.capabilities = capabilities; + } - public List<Map<String, ToscaRequirement>> getRequirements() { - return requirements; - } + public List<Map<String, ToscaRequirement>> getRequirements() { + return requirements; + } - public void setRequirements(List<Map<String, ToscaRequirement>> requirements) { - this.requirements = requirements; - } + public void setRequirements(List<Map<String, ToscaRequirement>> requirements) { + this.requirements = requirements; + } - public String getDerived_from() { - return derived_from; - } + public String getDerived_from() { + return derived_from; + } - public void setDerived_from(String derived_from) { - this.derived_from = derived_from; - } + public void setDerived_from(String derived_from) { + this.derived_from = derived_from; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public ToscaMetadata getMetadata() { - return metadata; - } + public ToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(ToscaMetadata metadata) { + this.metadata = metadata; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java index 8b5c60b1d4..e1ac69fbe0 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaProperty.java @@ -22,62 +22,62 @@ package org.openecomp.sdc.be.tosca.model; public class ToscaProperty { - private String type; - private Object _defaultp_; - private String description; - private Boolean required; - private EntrySchema entry_schema; - private String status; - - public EntrySchema getEntry_schema() { - return entry_schema; - } - - public void setEntry_schema(EntrySchema entry_schema) { - this.entry_schema = entry_schema; - } - - public ToscaProperty() { - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public Object getDefaultp() { - return _defaultp_; - } - - public void setDefaultp(Object defaultp) { - this._defaultp_ = defaultp; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Boolean getRequired() { - return required; - } - - public void setRequired(Boolean required) { - this.required = required; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } + private String type; + private Object _defaultp_; + private String description; + private Boolean required; + private EntrySchema entry_schema; + private String status; + + public EntrySchema getEntry_schema() { + return entry_schema; + } + + public void setEntry_schema(EntrySchema entry_schema) { + this.entry_schema = entry_schema; + } + + public ToscaProperty() { + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Object getDefaultp() { + return _defaultp_; + } + + public void setDefaultp(Object defaultp) { + this._defaultp_ = defaultp; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Boolean getRequired() { + return required; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java index 21fdc9f722..35d5c4e6e1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaRequirement.java @@ -25,21 +25,21 @@ import java.util.Map; public class ToscaRequirement extends ToscaTemplateRequirement { - private List<Object> occurrences; + private List<Object> occurrences; - public ToscaRequirement() { - } + public ToscaRequirement() { + } - public List<Object> getOccurrences() { - return occurrences; - } + public List<Object> getOccurrences() { + return occurrences; + } - public void setOccurrences(List<Object> occurrences) { - this.occurrences = occurrences; - } + public void setOccurrences(List<Object> occurrences) { + this.occurrences = occurrences; + } - public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException { - return super.toMap(); - } + public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException { + return super.toMap(); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java index e80d52167c..387238206c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplate.java @@ -20,71 +20,71 @@ package org.openecomp.sdc.be.tosca.model; -import java.util.List; -import java.util.Map; - import org.apache.commons.lang3.tuple.Triple; import org.openecomp.sdc.be.model.Component; +import java.util.List; +import java.util.Map; + public class ToscaTemplate { - private String tosca_definitions_version; - private ToscaMetadata metadata; - private List<Map<String, Map<String, String>>> imports; - private Map<String, ToscaNodeType> node_types; - private ToscaTopolgyTemplate topology_template; + private String tosca_definitions_version; + private ToscaMetadata metadata; + private List<Map<String, Map<String, String>>> imports; + private Map<String, ToscaNodeType> node_types; + private ToscaTopolgyTemplate topology_template; - private List<Triple<String, String, Component>> dependencies; + private List<Triple<String, String, Component>> dependencies; - public ToscaTemplate(String tosca_definitions_version) { - this.tosca_definitions_version = tosca_definitions_version; - } + public ToscaTemplate(String tosca_definitions_version) { + this.tosca_definitions_version = tosca_definitions_version; + } - public Map<String, ToscaNodeType> getNode_types() { - return node_types; - } + public Map<String, ToscaNodeType> getNode_types() { + return node_types; + } - public void setNode_types(Map<String, ToscaNodeType> node_types) { - this.node_types = node_types; - } + public void setNode_types(Map<String, ToscaNodeType> node_types) { + this.node_types = node_types; + } - public List<Map<String, Map<String, String>>> getImports() { - return imports; - } + public List<Map<String, Map<String, String>>> getImports() { + return imports; + } - public void setImports(List<Map<String, Map<String, String>>> imports) { - this.imports = imports; - } + public void setImports(List<Map<String, Map<String, String>>> imports) { + this.imports = imports; + } - public String getTosca_definitions_version() { - return tosca_definitions_version; - } + public String getTosca_definitions_version() { + return tosca_definitions_version; + } - public void setTosca_definitions_version(String tosca_definitions_version) { - this.tosca_definitions_version = tosca_definitions_version; - } + public void setTosca_definitions_version(String tosca_definitions_version) { + this.tosca_definitions_version = tosca_definitions_version; + } - public ToscaMetadata getMetadata() { - return metadata; - } + public ToscaMetadata getMetadata() { + return metadata; + } - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } + public void setMetadata(ToscaMetadata metadata) { + this.metadata = metadata; + } - public ToscaTopolgyTemplate getTopology_template() { - return topology_template; - } + public ToscaTopolgyTemplate getTopology_template() { + return topology_template; + } - public void setTopology_template(ToscaTopolgyTemplate topology_template) { - this.topology_template = topology_template; - } + public void setTopology_template(ToscaTopolgyTemplate topology_template) { + this.topology_template = topology_template; + } - public List<Triple<String, String, Component>> getDependencies() { - return dependencies; - } + public List<Triple<String, String, Component>> getDependencies() { + return dependencies; + } - public void setDependencies(List<Triple<String, String, Component>> dependencies) { - this.dependencies = dependencies; - } + public void setDependencies(List<Triple<String, String, Component>> dependencies) { + this.dependencies = dependencies; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java index 9adb9edfe1..68341079c1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateCapability.java @@ -24,23 +24,23 @@ import java.util.List; import java.util.Map; public class ToscaTemplateCapability { - private List<String> valid_source_types; - private Map<String, Object> properties; + private List<String> valid_source_types; + private Map<String, Object> properties; - public List<String> getValid_source_types() { - return valid_source_types; - } + public List<String> getValid_source_types() { + return valid_source_types; + } - public void setValid_source_types(List<String> valid_source_types) { - this.valid_source_types = valid_source_types; - } + public void setValid_source_types(List<String> valid_source_types) { + this.valid_source_types = valid_source_types; + } - public Map<String, Object> getProperties() { - return properties; - } + public Map<String, Object> getProperties() { + return properties; + } - public void setProperties(Map<String, Object> properties) { - this.properties = properties; - } + public void setProperties(Map<String, Object> properties) { + this.properties = properties; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java index 71bae81f9c..7a77c4f47c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTemplateRequirement.java @@ -25,44 +25,44 @@ import java.util.HashMap; import java.util.Map; public class ToscaTemplateRequirement { - private String capability; - private String node; - private String relationship; + private String capability; + private String node; + private String relationship; - public ToscaTemplateRequirement() { - } + public ToscaTemplateRequirement() { + } - public String getCapability() { - return capability; - } + public String getCapability() { + return capability; + } - public void setCapability(String capability) { - this.capability = capability; - } + public void setCapability(String capability) { + this.capability = capability; + } - public String getNode() { - return node; - } + public String getNode() { + return node; + } - public void setNode(String node) { - this.node = node; - } + public void setNode(String node) { + this.node = node; + } - public String getRelationship() { - return relationship; - } + public String getRelationship() { + return relationship; + } - public void setRelationship(String relationship) { - this.relationship = relationship; - } + public void setRelationship(String relationship) { + this.relationship = relationship; + } - public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException { - Map<String, Object> map = new HashMap<>(); - Field[] fields = this.getClass().getDeclaredFields(); - for (Field field : fields) { - field.setAccessible(true); - map.put(field.getName(), field.get(this)); - } - return map; - } + public Map<String, Object> toMap() throws IllegalArgumentException, IllegalAccessException { + Map<String, Object> map = new HashMap<>(); + Field[] fields = this.getClass().getDeclaredFields(); + for (Field field : fields) { + field.setAccessible(true); + map.put(field.getName(), field.get(this)); + } + return map; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java index df285c6ad9..8ef32cb06f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaTopolgyTemplate.java @@ -24,44 +24,44 @@ import java.util.HashMap; import java.util.Map; public class ToscaTopolgyTemplate { - private Map<String, ToscaProperty> inputs; - private Map<String, ToscaNodeTemplate> node_templates; - private Map<String, ToscaGroupTemplate> groups; - private SubstitutionMapping substitution_mappings; + private Map<String, ToscaProperty> inputs; + private Map<String, ToscaNodeTemplate> node_templates; + private Map<String, ToscaGroupTemplate> groups; + private SubstitutionMapping substitution_mappings; - public Map<String, ToscaNodeTemplate> getNode_templates() { - return node_templates; - } + public Map<String, ToscaNodeTemplate> getNode_templates() { + return node_templates; + } - public void setNode_templates(Map<String, ToscaNodeTemplate> node_templates) { - this.node_templates = node_templates; - } + public void setNode_templates(Map<String, ToscaNodeTemplate> node_templates) { + this.node_templates = node_templates; + } - public Map<String, ToscaGroupTemplate> getGroups() { - return groups; - } + public Map<String, ToscaGroupTemplate> getGroups() { + return groups; + } - public void addGroups(Map<String, ToscaGroupTemplate> groups) { - if ( this.groups == null ){ - this.groups = new HashMap<>(); - } - this.groups.putAll(groups); - } + public void addGroups(Map<String, ToscaGroupTemplate> groups) { + if ( this.groups == null ){ + this.groups = new HashMap<>(); + } + this.groups.putAll(groups); + } - public SubstitutionMapping getSubstitution_mappings() { - return substitution_mappings; - } + public SubstitutionMapping getSubstitution_mappings() { + return substitution_mappings; + } - public void setSubstitution_mappings(SubstitutionMapping substitution_mapping) { - this.substitution_mappings = substitution_mapping; - } + public void setSubstitution_mappings(SubstitutionMapping substitution_mapping) { + this.substitution_mappings = substitution_mapping; + } - public Map<String, ToscaProperty> getInputs() { - return inputs; - } + public Map<String, ToscaProperty> getInputs() { + return inputs; + } - public void setInputs(Map<String, ToscaProperty> inputs) { - this.inputs = inputs; - } + public void setInputs(Map<String, ToscaProperty> inputs) { + this.inputs = inputs; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java index 26ce118a1a..198e233fde 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/VfModuleToscaMetadata.java @@ -22,54 +22,54 @@ package org.openecomp.sdc.be.tosca.model; public class VfModuleToscaMetadata implements IToscaMetadata { - private String vfModuleModelName; - private String vfModuleModelInvariantUUID; - private String vfModuleModelUUID; - private String vfModuleModelVersion; - private String vfModuleModelCustomizationUUID; + private String vfModuleModelName; + private String vfModuleModelInvariantUUID; + private String vfModuleModelUUID; + private String vfModuleModelVersion; + private String vfModuleModelCustomizationUUID; - @Override - public void setName(String name) { - vfModuleModelName = name; - } + @Override + public void setName(String name) { + vfModuleModelName = name; + } - @Override - public void setInvariantUUID(String invariantUUID) { - vfModuleModelInvariantUUID = invariantUUID; - } + @Override + public void setInvariantUUID(String invariantUUID) { + vfModuleModelInvariantUUID = invariantUUID; + } - @Override - public void setUUID(String uUID) { - vfModuleModelUUID = uUID; - } + @Override + public void setUUID(String uUID) { + vfModuleModelUUID = uUID; + } - @Override - public void setVersion(String version) { - vfModuleModelVersion = version; - } + @Override + public void setVersion(String version) { + vfModuleModelVersion = version; + } - public String getVfModuleModelName() { - return vfModuleModelName; - } + public String getVfModuleModelName() { + return vfModuleModelName; + } - public String getVfModuleModelInvariantUUID() { - return vfModuleModelInvariantUUID; - } + public String getVfModuleModelInvariantUUID() { + return vfModuleModelInvariantUUID; + } - public String getVfModuleModelUUID() { - return vfModuleModelUUID; - } + public String getVfModuleModelUUID() { + return vfModuleModelUUID; + } - public String getVfModuleModelVersion() { - return vfModuleModelVersion; - } + public String getVfModuleModelVersion() { + return vfModuleModelVersion; + } - public String getVfModuleModelCustomizationUUID() { - return vfModuleModelCustomizationUUID; - } + public String getVfModuleModelCustomizationUUID() { + return vfModuleModelCustomizationUUID; + } - public void setCustomizationUUID(String customizationUUID) { - this.vfModuleModelCustomizationUUID = customizationUUID; - } + public void setCustomizationUUID(String customizationUUID) { + this.vfModuleModelCustomizationUUID = customizationUUID; + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java new file mode 100644 index 0000000000..c4905d005e --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/ForwardingPathToscaUtil.java @@ -0,0 +1,124 @@ +package org.openecomp.sdc.be.tosca.utils; + +import fj.data.Either; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.ForwardingPathElementDataDefinition; +import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.tosca.CapabiltyRequirementConvertor; +import org.openecomp.sdc.be.tosca.model.ToscaNodeTemplate; +import org.openecomp.sdc.be.tosca.model.ToscaTemplateRequirement; + +import java.util.*; + +/** + * @author KATYR + * @since November 19, 2017 + */ + +public class ForwardingPathToscaUtil { + public static final String FORWARDS_TO_TOSCA_NAME = + "org.openecomp.relationships.ForwardsTo"; + public static final String PROTOCOL = "protocol"; + public static final String PORTS_RANGE = "target_range"; + public static final String FORWARDER = "forwarder"; + + public static void addForwardingPaths(Service service, Map<String, ToscaNodeTemplate> + nodeTemplates, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) { + for (String forwardingPathName : service.getForwardingPaths().keySet()) { + ToscaNodeTemplate forwardingPathNodeTemplate = + new ToscaNodeTemplate(); + final ForwardingPathDataDefinition path = + service.getForwardingPaths().get(forwardingPathName); + forwardingPathNodeTemplate.setType(path.getToscaResourceName()); + + if (Objects.nonNull(path.getDescription())) { + forwardingPathNodeTemplate.setDescription(path + .getDescription()); + } + Map<String, Object> props = new HashMap<>(); + if (Objects.nonNull(path.getDestinationPortNumber())) { + props.put(PORTS_RANGE, Collections.singletonList(path.getDestinationPortNumber())); + } + if (Objects.nonNull(path.getProtocol())) { + props.put(PROTOCOL, path.getProtocol()); + } + if (MapUtils.isNotEmpty(props)) { + forwardingPathNodeTemplate.setProperties(props); + } + + final List<ForwardingPathElementDataDefinition> pathElements = + path.getPathElements() + .getListToscaDataDefinition(); + forwardingPathNodeTemplate.setRequirements(convertPathElementsToRequirements(pathElements, + service, capabiltyRequirementConvertor, originComponents, toscaOperationFacade)); + + nodeTemplates.put(path.getName(), forwardingPathNodeTemplate); + } + + } + + private static List<Map<String, ToscaTemplateRequirement>> convertPathElementsToRequirements( + List<ForwardingPathElementDataDefinition> pathElements, Service service, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map<String, Component> originComponents,ToscaOperationFacade toscaOperationFacade) { + List<Map<String, ToscaTemplateRequirement>> toscaRequirements = new ArrayList<>(); + for (int i = 0; i <= pathElements.size() -1 ; i++) { + final ForwardingPathElementDataDefinition element = pathElements.get(i); + toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getFromNode(), element.getFromCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element.getFromNode()))); + if ( i == pathElements.size() -1) { + toscaRequirements.add(handleSingleReq(fetchCPName(service, element.getToNode(), element.getToCP(), capabiltyRequirementConvertor, originComponents, toscaOperationFacade), fetchNodeName(service, element + .getToNode()))); + } + } + return toscaRequirements; + + } + + private static String fetchNodeName(Service service, String nodeId) { + if (service.getComponentInstanceById(nodeId).isPresent()) { + return service.getComponentInstanceById(nodeId).get().getName(); + } else { + return ""; + } + } + + + private static Map<String, ToscaTemplateRequirement> handleSingleReq( + String fromCP, String fromNode) { + Map<String, ToscaTemplateRequirement> toscaReqMap = new HashMap<>(); + ToscaTemplateRequirement firstReq = new ToscaTemplateRequirement(); + firstReq.setRelationship(FORWARDS_TO_TOSCA_NAME); //todo + firstReq.setCapability(fromCP); + firstReq.setNode(fromNode); + toscaReqMap.put(FORWARDER, firstReq); + + return toscaReqMap; + } + + /** + * @todo handle errors. + */ + private static String fetchCPName(Service service, String nodeID, String cpName, CapabiltyRequirementConvertor capabiltyRequirementConvertor, Map<String, Component> originComponents, ToscaOperationFacade toscaOperationFacade) { + Optional<ComponentInstance> componentInstance = service.getComponentInstanceById(nodeID); + ComponentInstance componentInstanceVal = componentInstance.get(); + String name = componentInstanceVal.getNormalizedName(); + Component component = originComponents.get(componentInstanceVal.getComponentUid()); + if(componentInstanceVal.getIsProxy()){ + component = originComponents.get(componentInstanceVal.getSourceModelUid()); + if (component == null) { + component = toscaOperationFacade.getToscaFullElement(componentInstanceVal.getSourceModelUid()).left().value(); + } + + } + CapabilityDefinition capability = componentInstanceVal.getCapabilities().values().stream().flatMap(capabilityDefinitions -> capabilityDefinitions.stream()) + .filter(capabilityDefinition -> capabilityDefinition.getUniqueId().equals(cpName)).findAny().get(); + List<String> path = capability.getPath(); + List<String> reducedPath = new ArrayList<>(path); + reducedPath.remove(reducedPath.size() - 1); + Either<String, Boolean> stringBooleanEither = capabiltyRequirementConvertor.buildSubstitutedName(originComponents, component, reducedPath, capability.getName()); + return name + "." + stringBooleanEither.left().value(); + } +} |