diff options
Diffstat (limited to 'openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services')
9 files changed, 1931 insertions, 0 deletions
diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java new file mode 100644 index 0000000000..d0d7ccf621 --- /dev/null +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java @@ -0,0 +1,588 @@ +/*- + * ============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.tosca.services; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; +import org.openecomp.sdc.tosca.datatypes.model.Constraint; +import org.openecomp.sdc.tosca.datatypes.model.EntrySchema; +import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; +import org.openecomp.sdc.tosca.datatypes.model.Metadata; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.PolicyDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; +import org.openecomp.sdc.tosca.datatypes.model.RelationshipTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.Status; +import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping; +import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate; +import org.openecomp.sdc.tosca.datatypes.model.heatextend.ParameterDefinitionExt; +import org.openecomp.sdc.tosca.errors.InvalidAddActionNullEntityErrorBuilder; +import org.openecomp.sdc.tosca.errors.InvalidRequirementAssignmentErrorBuilder; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * The type Data model util. + */ +public class DataModelUtil { + + /** + * Add substitution mapping. + * + * @param serviceTemplate the service template + * @param substitutionMapping the substitution mapping + */ + public static void addSubstitutionMapping(ServiceTemplate serviceTemplate, + SubstitutionMapping substitutionMapping) { + if (serviceTemplate == null) { + throw new CoreException( + new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping", "Service Template") + .build()); + } + + if (serviceTemplate.getTopology_template() == null) { + serviceTemplate.setTopology_template(new TopologyTemplate()); + } + serviceTemplate.getTopology_template().setSubstitution_mappings(substitutionMapping); + } + + /** + * Add substitution mapping req. + * + * @param serviceTemplate the service template + * @param substitutionMappingRequirementId the substitution mapping requirement id + * @param substitutionMappingRequirementList the substitution mapping requirement list + */ + public static void addSubstitutionMappingReq(ServiceTemplate serviceTemplate, + String substitutionMappingRequirementId, + List<String> substitutionMappingRequirementList) { + if (serviceTemplate == null) { + throw new CoreException( + new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Requirements", + "Service Template").build()); + } + + if (serviceTemplate.getTopology_template() == null) { + serviceTemplate.setTopology_template(new TopologyTemplate()); + } + if (serviceTemplate.getTopology_template().getSubstitution_mappings() == null) { + serviceTemplate.getTopology_template().setSubstitution_mappings(new SubstitutionMapping()); + } + if (serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() + == null) { + serviceTemplate.getTopology_template().getSubstitution_mappings() + .setRequirements(new HashMap<>()); + } + + serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() + .put(substitutionMappingRequirementId, substitutionMappingRequirementList); + } + + /** + * Add node template. + * + * @param serviceTemplate the service template + * @param nodeTemplateId the node template id + * @param nodeTemplate the node template + */ + public static void addNodeTemplate(ServiceTemplate serviceTemplate, String nodeTemplateId, + NodeTemplate nodeTemplate) { + if (serviceTemplate == null) { + throw new CoreException( + new InvalidAddActionNullEntityErrorBuilder("Node Template", "Service Template").build()); + } + TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template(); + if (Objects.isNull(topologyTemplate)) { + topologyTemplate = new TopologyTemplate(); + serviceTemplate.setTopology_template(topologyTemplate); + } + if (topologyTemplate.getNode_templates() == null) { + topologyTemplate.setNode_templates(new HashMap<>()); + } + topologyTemplate.getNode_templates().put(nodeTemplateId, nodeTemplate); + } + + /** + * Add policy definition. + * + * @param serviceTemplate the service template + * @param policyId the policy id + * @param policyDefinition the policy definition + */ + public static void addPolicyDefinition(ServiceTemplate serviceTemplate, String policyId, + PolicyDefinition policyDefinition) { + if (serviceTemplate == null) { + throw new CoreException( + new InvalidAddActionNullEntityErrorBuilder("Policy Definition", "Service Template") + .build()); + } + TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template(); + if (Objects.isNull(topologyTemplate)) { + topologyTemplate = new TopologyTemplate(); + serviceTemplate.setTopology_template(topologyTemplate); + } + if (topologyTemplate.getPolicies() == null) { + topologyTemplate.setPolicies(new HashMap<>()); + } + topologyTemplate.getPolicies().put(policyId, policyDefinition); + } + + /** + * Add node type. + * + * @param serviceTemplate the service template + * @param nodeTypeId the node type id + * @param nodeType the node type + */ + public static void addNodeType(ServiceTemplate serviceTemplate, String nodeTypeId, + NodeType nodeType) { + if (serviceTemplate == null) { + throw new CoreException( + new InvalidAddActionNullEntityErrorBuilder("Node Type", "Service Template").build()); + } + if (serviceTemplate.getNode_types() == null) { + serviceTemplate.setNode_types(new HashMap<>()); + } + serviceTemplate.getNode_types().put(nodeTypeId, nodeType); + } + + /** + * Add relationship template. + * + * @param serviceTemplate the service template + * @param relationshipTemplateId the relationship template id + * @param relationshipTemplate the relationship template + */ + public static void addRelationshipTemplate(ServiceTemplate serviceTemplate, + String relationshipTemplateId, + RelationshipTemplate relationshipTemplate) { + if (serviceTemplate == null) { + throw new CoreException( + new InvalidAddActionNullEntityErrorBuilder("Relationship Template", "Service Template") + .build()); + } + if (serviceTemplate.getTopology_template() == null) { + serviceTemplate.setTopology_template(new TopologyTemplate()); + } + if (serviceTemplate.getTopology_template().getRelationship_templates() == null) { + serviceTemplate.getTopology_template().setRelationship_templates(new HashMap<>()); + } + serviceTemplate.getTopology_template().getRelationship_templates() + .put(relationshipTemplateId, relationshipTemplate); + } + + /** + * Add requirement assignment. + * + * @param nodeTemplate the node template + * @param requirementId the requirement id + * @param requirementAssignment the requirement assignment + */ + public static void addRequirementAssignment(NodeTemplate nodeTemplate, String requirementId, + RequirementAssignment requirementAssignment) { + if (nodeTemplate == null) { + throw new CoreException( + new InvalidAddActionNullEntityErrorBuilder("Requirement Assignment", "Node Template") + .build()); + } + if (requirementAssignment.getNode() == null) { + throw new CoreException(new InvalidRequirementAssignmentErrorBuilder(requirementId).build()); + } + + if (nodeTemplate.getRequirements() == null) { + nodeTemplate.setRequirements(new ArrayList<>()); + } + Map<String, RequirementAssignment> requirement = new HashMap<>(); + requirement.put(requirementId, requirementAssignment); + nodeTemplate.getRequirements().add(requirement); + } + + /** + * Gets node template. + * + * @param serviceTemplate the service template + * @param nodeTemplateId the node template id + * @return the node template + */ + public static NodeTemplate getNodeTemplate(ServiceTemplate serviceTemplate, + String nodeTemplateId) { + if (serviceTemplate == null + || serviceTemplate.getTopology_template() == null + || serviceTemplate.getTopology_template().getNode_templates() == null) { + return null; + } + return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId); + } + + /** + * Gets node type. + * + * @param serviceTemplate the service template + * @param nodeTypeId the node type id + * @return the node type + */ + public static NodeType getNodeType(ServiceTemplate serviceTemplate, String nodeTypeId) { + if (serviceTemplate == null || serviceTemplate.getNode_types() == null) { + return null; + } + return serviceTemplate.getNode_types().get(nodeTypeId); + } + + /** + * Add group definition to topology template. + * + * @param serviceTemplate the service template + * @param groupName the group name + * @param group the group + */ + public static void addGroupDefinitionToTopologyTemplate(ServiceTemplate serviceTemplate, + String groupName, GroupDefinition group) { + if (serviceTemplate == null) { + throw new CoreException( + new InvalidAddActionNullEntityErrorBuilder("Group Definition", "Service Template") + .build()); + } + + TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template(); + if (Objects.isNull(topologyTemplate)) { + topologyTemplate = new TopologyTemplate(); + serviceTemplate.setTopology_template(topologyTemplate); + } + if (topologyTemplate.getGroups() == null) { + topologyTemplate.setGroups(new HashMap<>()); + } + if (serviceTemplate.getTopology_template().getGroups() == null) { + Map<String, GroupDefinition> groups = new HashMap<>(); + serviceTemplate.getTopology_template().setGroups(groups); + } + serviceTemplate.getTopology_template().getGroups().put(groupName, group); + } + + /** + * Create property definition property definition. + * + * @param type the type + * @param description the description + * @param required the required + * @param constraints the constraints + * @param status the status + * @param entrySchema the entry schema + * @param defaultVal the default val + * @return the property definition + */ + public static PropertyDefinition createPropertyDefinition(String type, String description, + boolean required, + List<Constraint> constraints, + Status status, + EntrySchema entrySchema, + Object defaultVal) { + PropertyDefinition propDef = new PropertyDefinition(); + propDef.setType(type); + propDef.setDescription(description); + propDef.setRequired(required); + propDef.setConstraints(constraints); + if (status != null) { + propDef.setStatus(status); + } + propDef.setEntry_schema(entrySchema); + propDef.set_default(defaultVal); + + return propDef; + } + + /** + * Create requirement requirement definition. + * + * @param capability the capability + * @param node the node + * @param relationship the relationship + * @param occurrences the occurrences + * @return the requirement definition + */ + public static RequirementDefinition createRequirement(String capability, String node, + String relationship, Object[] occurrences) { + RequirementDefinition requirementDefinition = new RequirementDefinition(); + requirementDefinition.setCapability(capability); + requirementDefinition.setNode(node); + requirementDefinition.setRelationship(relationship); + if (occurrences != null) { + requirementDefinition.setOccurrences(occurrences); + } + return requirementDefinition; + } + + /** + * Create attribute definition attribute definition. + * + * @param type the type + * @param description the description + * @param status the status + * @param entrySchema the entry schema + * @param defaultVal the default val + * @return the attribute definition + */ + public static AttributeDefinition createAttributeDefinition(String type, String description, + Status status, + EntrySchema entrySchema, + Object defaultVal) { + AttributeDefinition attributeDef = new AttributeDefinition(); + attributeDef.setType(type); + + if (description != null) { + attributeDef.setDescription(description); + } + if (status != null) { + attributeDef.setStatus(status); + } + attributeDef.setEntry_schema(entrySchema); + attributeDef.set_default(defaultVal); + + return attributeDef; + } + + /** + * Create valid values constraint constraint. + * + * @param values the values + * @return the constraint + */ + public static Constraint createValidValuesConstraint(Object... values) { + Constraint validValues = new Constraint(); + for (Object value : values) { + validValues.addValidValue(value); + } + return validValues; + } + + /** + * Create metadata metadata. + * + * @param templateName the template name + * @param templateVersion the template version + * @param templateAuthor the template author + * @return the metadata + */ + public static Metadata createMetadata(String templateName, String templateVersion, + String templateAuthor) { + Metadata metadata = new Metadata(); + metadata.setTemplate_name(templateName); + metadata.setTemplate_version(templateVersion); + metadata.setTemplate_author(templateAuthor); + + return metadata; + } + + /** + * Create entry schema entry schema. + * + * @param type the type + * @param description the description + * @param constraints the constraints + * @return the entry schema + */ + public static EntrySchema createEntrySchema(String type, String description, + List<Constraint> constraints) { + EntrySchema entrySchema = new EntrySchema(); + entrySchema.setType(type); + entrySchema.setDescription(description); + entrySchema.setConstraints(constraints); + return entrySchema; + } + + /** + * Create valid values constraints list list. + * + * @param values the values + * @return the list + */ + public static List<Constraint> createValidValuesConstraintsList(String... values) { + List<Constraint> constraints; + Constraint validValues; + constraints = new ArrayList<>(); + validValues = DataModelUtil.createValidValuesConstraint(values); + constraints.add(validValues); + return constraints; + } + + /** + * Create greater or equal constrain constraint. + * + * @param value the value + * @return the constraint + */ + public static Constraint createGreaterOrEqualConstrain(Object value) { + + Constraint constraint = new Constraint(); + constraint.setGreater_or_equal(value); + return constraint; + } + + /** + * Gets constrain list. + * + * @param constrains the constrains + * @return the constrain list + */ + public static List<Constraint> getConstrainList(Constraint... constrains) { + return Arrays.asList(constrains); + + } + + /** + * Create get input property value from list parameter map. + * + * @param inputPropertyListName the input property list name + * @param indexInTheList the index in the list + * @param nestedPropertyName the nested property name + * @return the map + */ + public static Map createGetInputPropertyValueFromListParameter(String inputPropertyListName, + int indexInTheList, + String... nestedPropertyName) { + List propertyList = new ArrayList<>(); + propertyList.add(inputPropertyListName); + propertyList.add(indexInTheList); + if (nestedPropertyName != null) { + Collections.addAll(propertyList, nestedPropertyName); + } + Map getInputProperty = new HashMap<>(); + getInputProperty.put(ToscaFunctions.GET_INPUT.getDisplayName(), propertyList); + return getInputProperty; + } + + /** + * Convert property def to parameter def parameter definition ext. + * + * @param propertyDefinition the property definition + * @return the parameter definition ext + */ + public static ParameterDefinitionExt convertPropertyDefToParameterDef( + PropertyDefinition propertyDefinition) { + if (propertyDefinition == null) { + return null; + } + + ParameterDefinitionExt parameterDefinition = new ParameterDefinitionExt(); + parameterDefinition.setType(propertyDefinition.getType()); + parameterDefinition.setDescription(propertyDefinition.getDescription()); + parameterDefinition.setRequired(propertyDefinition.getRequired()); + parameterDefinition.set_default(propertyDefinition.get_default()); + parameterDefinition.setStatus(propertyDefinition.getStatus()); + parameterDefinition.setConstraints(propertyDefinition.getConstraints()); + parameterDefinition.setEntry_schema(propertyDefinition.getEntry_schema()); + parameterDefinition.setHidden(false); + parameterDefinition.setImmutable(false); + + return parameterDefinition; + } + + /** + * Convert attribute def to parameter def parameter definition ext. + * + * @param attributeDefinition the attribute definition + * @param outputValue the output value + * @return the parameter definition ext + */ + public static ParameterDefinitionExt convertAttributeDefToParameterDef( + AttributeDefinition attributeDefinition, Map<String, List> outputValue) { + if (attributeDefinition == null) { + return null; + } + ParameterDefinitionExt parameterDefinition = new ParameterDefinitionExt(); + parameterDefinition.setDescription(attributeDefinition.getDescription()); + parameterDefinition.setValue(outputValue); + return parameterDefinition; + } + + /** + * Clone constraints list. + * + * @param constraints the constraints + * @return the list + */ + public static List<Constraint> cloneConstraints(List<Constraint> constraints) { + if (constraints == null) { + return null; + } + return constraints.stream().map(Constraint::clone).collect(Collectors.toList()); + } + + /** + * Clone valid source types list. + * + * @param validSourceTypes the valid source types + * @return the list + */ + public static List<String> cloneValidSourceTypes(List<String> validSourceTypes) { + if (validSourceTypes == null) { + return null; + } + return validSourceTypes.stream().collect(Collectors.toList()); + } + + /** + * Clone property definitions map. + * + * @param propertyDefinitions the property definitions + * @return the map + */ + public static Map<String, PropertyDefinition> clonePropertyDefinitions( + Map<String, PropertyDefinition> propertyDefinitions) { + if (propertyDefinitions == null) { + return null; + } + Map<String, PropertyDefinition> clonedProperties = new HashMap<>(); + for (String propertyKey : propertyDefinitions.keySet()) { + clonedProperties.put(propertyKey, propertyDefinitions.get(propertyKey).clone()); + } + return clonedProperties; + } + + /** + * Clone attribute definitions map. + * + * @param attributeDefinitions the attribute definitions + * @return the map + */ + public static Map<String, AttributeDefinition> cloneAttributeDefinitions( + Map<String, AttributeDefinition> attributeDefinitions) { + if (attributeDefinitions == null) { + return null; + } + Map<String, AttributeDefinition> clonedAttributeDefinitions = new HashMap<>(); + for (String attributeKey : attributeDefinitions.keySet()) { + clonedAttributeDefinitions.put(attributeKey, attributeDefinitions.get(attributeKey).clone()); + } + return clonedAttributeDefinitions; + } +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java new file mode 100644 index 0000000000..271c471922 --- /dev/null +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java @@ -0,0 +1,66 @@ +/*- + * ============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.tosca.services; + +import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public interface ToscaAnalyzerService { + + /* + node template with type equal to node type or derived from node type + */ + Map<String, NodeTemplate> getNodeTemplatesByType(ServiceTemplate serviceTemplate, String nodeType, + ToscaServiceModel toscaServiceModel); + + boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType, ServiceTemplate serviceTemplate, + ToscaServiceModel toscaServiceModel); + + List<RequirementAssignment> getRequirements(NodeTemplate nodeTemplate, String requirementId); + + Optional<NodeTemplate> getNodeTemplateById(ServiceTemplate serviceTemplate, + String nodeTemplateId); + + Optional<String> getSubstituteServiceTemplateName(String substituteNodeTemplateId, + NodeTemplate substitutableNodeTemplate); + + Map<String, NodeTemplate> getSubstitutableNodeTemplates(ServiceTemplate serviceTemplate); + + Optional<Map.Entry<String, NodeTemplate>> getSubstitutionMappedNodeTemplateByExposedReq( + String substituteServiceTemplateFileName, ServiceTemplate substituteServiceTemplate, + String requirementId); + + /* + match only for the input which is not null + */ + boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment, + String capability, String node, String relationship); + + Object getFlatEntity(ToscaElementTypes elementType, String type, ServiceTemplate serviceTemplate, + ToscaServiceModel toscaModel); +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java new file mode 100644 index 0000000000..27cf07e166 --- /dev/null +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java @@ -0,0 +1,65 @@ +/*- + * ============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.tosca.services; + + +public class ToscaConstants { + + //TOSCA Node Types prefix + public static final String NODES_PREFIX = "org.openecomp.resource.vfc.nodes.heat."; + public static final String NODES_SUBSTITUTION_PREFIX + = "org.openecomp.resource.abstract.nodes.heat."; + + //TOSCA Requirement Ids + public static final String DEPENDS_ON_REQUIREMENT_ID = "dependency"; + public static final String BINDING_REQUIREMENT_ID = "binding"; + public static final String LINK_REQUIREMENT_ID = "link"; + public static final String LOCAL_STORAGE_REQUIREMENT_ID = "local_storage"; + public static final String NETWORK_REQUIREMENT_ID = "network"; + public static final String PORT_REQUIREMENT_ID = "port"; + + //TOSCA Capability Ids + public static final String BINDING_CAPABILITY_ID = "binding"; + public static final String LINK_CAPABILITY_ID = "link"; + public static final String HOST_CAPABILITY_ID = "host"; + public static final String ENDPOINT_CAPABILITY_ID = "endpoint"; + public static final String OS_CAPABILITY_ID = "os"; + public static final String SCALABLE_CAPABILITY_ID = "scalable"; + + //General + public static final String TOSCA_DEFINITIONS_VERSION = "tosca_simple_yaml_1_0_0"; + public static final String MODELABLE_ENTITY_NAME_SELF = "SELF"; + public static final String NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE = "substitutable"; + public static final String NATIVE_TYPES_SERVICE_TEMPLATE_NAME = "NativeTypesServiceTemplate"; + public static final String UNBOUNDED = "UNBOUNDED"; + + //properties + public static final String SERVICE_TEMPLATE_FILTER_PROPERTY_NAME = "service_template_filter"; + public static final String SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME = + "substitute_service_template"; + public static final String COUNT_PROPERTY_NAME = "count"; + public static final String INDEX_VALUE_PROPERTY_NAME = "index_value"; + public static final String SCALING_ENABLED_PROPERTY_NAME = "scaling_enabled"; + + public static final String DHCP_ENABLED_PROPERTY_NAME = "dhcp_enabled"; + + +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaFileOutputService.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaFileOutputService.java new file mode 100644 index 0000000000..7ec2fffa2b --- /dev/null +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaFileOutputService.java @@ -0,0 +1,34 @@ +/*- + * ============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.tosca.services; + +import org.openecomp.core.utilities.file.FileContentHandler; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; + +public interface ToscaFileOutputService { + byte[] createOutputFile(ToscaServiceModel toscaServiceModel, + FileContentHandler externalArtifacts); + + String createMetaFile(String entryDefinitionsFileName); + + String getArtifactsFolderName(); + +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaNativeTypesServiceTemplate.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaNativeTypesServiceTemplate.java new file mode 100644 index 0000000000..013d761168 --- /dev/null +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaNativeTypesServiceTemplate.java @@ -0,0 +1,309 @@ +/*- + * ============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.tosca.services; + +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaDataType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; + +import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.openecomp.sdc.tosca.datatypes.model.InterfaceDefinition; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PropertyType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The type Tosca native types service template. + */ +public class ToscaNativeTypesServiceTemplate { + /** + * Create service template service template. + * + * @return the service template + */ + public static ServiceTemplate createServiceTemplate() { + ServiceTemplate nativeNodeTypesServiceTemplate = new ServiceTemplate(); + nativeNodeTypesServiceTemplate + .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); + nativeNodeTypesServiceTemplate.setMetadata(DataModelUtil + .createMetadata(ToscaConstants.NATIVE_TYPES_SERVICE_TEMPLATE_NAME, "1.0.0", null)); + nativeNodeTypesServiceTemplate.setDescription("TOSCA Native Node Types"); + nativeNodeTypesServiceTemplate.setNode_types(createNativeNodeTypes()); + return nativeNodeTypesServiceTemplate; + } + + private static Map<String, NodeType> createNativeNodeTypes() { + Map<String, NodeType> nativeNodeTypes = new HashMap<>(); + nativeNodeTypes.put(ToscaNodeType.COMPUTE.getDisplayName(), createToscaNodesComputeNodeType()); + nativeNodeTypes.put(ToscaNodeType.ROOT.getDisplayName(), createToscaNodesRootNodeType()); + nativeNodeTypes + .put(ToscaNodeType.NETWORK_PORT.getDisplayName(), createToscaNodesPortsNodeType()); + nativeNodeTypes + .put(ToscaNodeType.BLOCK_STORAGE.getDisplayName(), createToscaNodesBlockStorageNodeType()); + nativeNodeTypes.put(ToscaNodeType.NETWORK.getDisplayName(), createToscaNodesNetworkNodeType()); + return nativeNodeTypes; + } + + private static NodeType createToscaNodesComputeNodeType() { + NodeType computeNodeType = new NodeType(); + computeNodeType.setDerived_from(ToscaNodeType.ROOT.getDisplayName()); + computeNodeType.setAttributes(createComputeAttributes()); + computeNodeType.setRequirements(createComputeRequirements()); + computeNodeType.setCapabilities(createComputeCapabilities()); + return computeNodeType; + } + + private static NodeType createToscaNodesRootNodeType() { + NodeType computeNodeType = new NodeType(); + computeNodeType.setAttributes(createRootAttributes()); + computeNodeType.setInterfaces(createRootInterfaces()); + return computeNodeType; + } + + private static NodeType createToscaNodesPortsNodeType() { + NodeType computeNodeType = new NodeType(); + computeNodeType.setDerived_from(ToscaNodeType.ROOT.getDisplayName()); + computeNodeType.setProperties(createToscaNodesPortProperties()); + computeNodeType.setRequirements(createToscaNodesPortRequirements()); + return computeNodeType; + } + + private static NodeType createToscaNodesBlockStorageNodeType() { + NodeType computeNodeType = new NodeType(); + computeNodeType.setDerived_from(ToscaNodeType.ROOT.getDisplayName()); + computeNodeType.setProperties(createToscaNodesBlockStorageProperties()); + computeNodeType.setCapabilities(createToscaNodesBlockStorageCapabilities()); + return computeNodeType; + } + + private static NodeType createToscaNodesNetworkNodeType() { + NodeType computeNodeType = new NodeType(); + computeNodeType.setDerived_from(ToscaNodeType.ROOT.getDisplayName()); + computeNodeType.setProperties(createToscaNodesNetworkProperties()); + computeNodeType.setCapabilities(createToscaNodesNetworkCapabilities()); + return computeNodeType; + } + + private static Map<String, PropertyDefinition> createToscaNodesPortProperties() { + Map<String, PropertyDefinition> propertyDefinitionMap = new HashMap<>(); + propertyDefinitionMap.put("ip_address", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("order", DataModelUtil + .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), null, true, + DataModelUtil.getConstrainList(DataModelUtil.createGreaterOrEqualConstrain(0)), null, + null, 0)); + propertyDefinitionMap.put("is_default", DataModelUtil + .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), null, false, null, null, + null, false)); + propertyDefinitionMap.put("ip_range_start", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("ip_range_end", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + return propertyDefinitionMap; + } + + private static Map<String, PropertyDefinition> createToscaNodesBlockStorageProperties() { + Map<String, PropertyDefinition> propertyDefinitionMap = new HashMap<>(); + propertyDefinitionMap.put("size", DataModelUtil + .createPropertyDefinition(PropertyType.SCALAR_UNIT_SIZE.getDisplayName(), null, false, + DataModelUtil.getConstrainList(DataModelUtil.createGreaterOrEqualConstrain("1 MB")), + null, null, null)); + propertyDefinitionMap.put("volume_id", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("snapshot_id", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + return propertyDefinitionMap; + } + + private static Map<String, PropertyDefinition> createToscaNodesNetworkProperties() { + Map<String, PropertyDefinition> propertyDefinitionMap = new HashMap<>(); + propertyDefinitionMap.put("ip_version", DataModelUtil + .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), null, false, + DataModelUtil.getConstrainList(DataModelUtil.createValidValuesConstraint(4, 6)), null, + null, 4)); + propertyDefinitionMap.put("cidr", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("start_ip", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("end_ip", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("gateway_ip", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("network_name", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("network_id", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("segmentation_id", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("network_type", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("physical_network", DataModelUtil + .createPropertyDefinition(PropertyType.STRING.getDisplayName(), null, false, null, null, + null, null)); + propertyDefinitionMap.put("dhcp_enabled", DataModelUtil + .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), null, false, null, null, + null, true)); + + return propertyDefinitionMap; + } + + private static Map<String, InterfaceDefinition> createRootInterfaces() { + return new HashMap<>(); + } + + private static Map<String, CapabilityDefinition> createComputeCapabilities() { + Map<String, CapabilityDefinition> computeCapabilities = new HashMap<>(); + computeCapabilities.put(ToscaConstants.HOST_CAPABILITY_ID, + createCapabilityDefinition(ToscaCapabilityType.CONTAINER.getDisplayName(), + createValidSourceTypes("tosca.nodes.SoftwareComponent"))); + computeCapabilities.put(ToscaConstants.ENDPOINT_CAPABILITY_ID, + createCapabilityDefinition(ToscaCapabilityType.ENDPOINT_ADMIN.getDisplayName(), null)); + computeCapabilities.put(ToscaConstants.OS_CAPABILITY_ID, + createCapabilityDefinition(ToscaCapabilityType.OPERATING_SYSTEM.getDisplayName(), null)); + computeCapabilities.put(ToscaConstants.SCALABLE_CAPABILITY_ID, + createCapabilityDefinition(ToscaCapabilityType.SCALABLE.getDisplayName(), null)); + computeCapabilities.put(ToscaConstants.BINDING_CAPABILITY_ID, + createCapabilityDefinition(ToscaCapabilityType.NETWORK_BINDABLE.getDisplayName(), null)); + return computeCapabilities; + } + + private static Map<String, CapabilityDefinition> createToscaNodesBlockStorageCapabilities() { + Map<String, CapabilityDefinition> computeCapabilities = new HashMap<>(); + computeCapabilities.put("attachment", + createCapabilityDefinition(ToscaCapabilityType.ATTACHMENT.getDisplayName(), null)); + return computeCapabilities; + } + + private static Map<String, CapabilityDefinition> createToscaNodesNetworkCapabilities() { + Map<String, CapabilityDefinition> computeCapabilities = new HashMap<>(); + computeCapabilities.put(ToscaConstants.LINK_CAPABILITY_ID, + createCapabilityDefinition(ToscaCapabilityType.NETWORK_LINKABLE.getDisplayName(), null)); + return computeCapabilities; + } + + private static List<String> createValidSourceTypes(String... validSourceTypes) { + return Arrays.asList(validSourceTypes); + } + + private static CapabilityDefinition createCapabilityDefinition(String type, + List<String> validSourceTypes) { + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setType(type); + capabilityDefinition.setValid_source_types(validSourceTypes); + return capabilityDefinition; + } + + private static List<Map<String, RequirementDefinition>> createComputeRequirements() { + List<Map<String, RequirementDefinition>> computeRequirementList = new ArrayList<>(); + Map<String, RequirementDefinition> localStorageRequirement = new HashMap<>(); + localStorageRequirement.put("local_storage", DataModelUtil + .createRequirement(ToscaCapabilityType.ATTACHMENT.getDisplayName(), + ToscaNodeType.BLOCK_STORAGE.getDisplayName(), + ToscaRelationshipType.NATIVE_ATTACHES_TO.getDisplayName(), + createOccurrences(0, ToscaConstants.UNBOUNDED))); + computeRequirementList.add(localStorageRequirement); + return computeRequirementList; + } + + private static List<Map<String, RequirementDefinition>> createToscaNodesPortRequirements() { + List<Map<String, RequirementDefinition>> requirements = new ArrayList<>(); + + Map<String, RequirementDefinition> linkRequirement = new HashMap<>(); + linkRequirement.put(ToscaConstants.LINK_REQUIREMENT_ID, DataModelUtil + .createRequirement(ToscaCapabilityType.NETWORK_LINKABLE.getDisplayName(), + ToscaNodeType.ROOT.getDisplayName(), + ToscaRelationshipType.NETWORK_LINK_TO.getDisplayName(), null)); + requirements.add(linkRequirement); + + Map<String, RequirementDefinition> bindingRequirement = new HashMap<>(); + bindingRequirement.put(ToscaConstants.BINDING_REQUIREMENT_ID, DataModelUtil + .createRequirement(ToscaCapabilityType.NETWORK_BINDABLE.getDisplayName(), + ToscaNodeType.ROOT.getDisplayName(), + ToscaRelationshipType.NETWORK_BINDS_TO.getDisplayName(), null)); + requirements.add(bindingRequirement); + + return requirements; + } + + + private static Object[] createOccurrences(Object min, Object max) { + return new Object[]{min, max}; + + } + + private static Map<String, AttributeDefinition> createComputeAttributes() { + Map<String, AttributeDefinition> computeAttributesDefMap = new HashMap<>(); + computeAttributesDefMap.put("private_address", DataModelUtil + .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "private address", null, + null, null)); + computeAttributesDefMap.put("public_address", DataModelUtil + .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "public_address", null, + null, null)); + computeAttributesDefMap.put("networks", DataModelUtil + .createAttributeDefinition(PropertyType.MAP.getDisplayName(), "networks", null, + DataModelUtil + .createEntrySchema(ToscaDataType.NETWORK_NETWORK_INFO.getDisplayName(), null, null), + null)); + computeAttributesDefMap.put("ports", DataModelUtil + .createAttributeDefinition(PropertyType.MAP.getDisplayName(), "ports", null, DataModelUtil + .createEntrySchema(ToscaDataType.NETWORK_PORT_INFO.getDisplayName(), null, null), + null)); + return computeAttributesDefMap; + } + + private static Map<String, AttributeDefinition> createRootAttributes() { + Map<String, AttributeDefinition> attributesDefMap = new HashMap<>(); + attributesDefMap.put("tosca_id", DataModelUtil + .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "tosca id", null, null, + null)); + attributesDefMap.put("tosca_name", DataModelUtil + .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "tosca name", null, null, + null)); + attributesDefMap.put("state", DataModelUtil + .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "state", null, null, + null)); + return attributesDefMap; + } + +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaUtil.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaUtil.java new file mode 100644 index 0000000000..4f9c70267d --- /dev/null +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaUtil.java @@ -0,0 +1,151 @@ +/*- + * ============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.tosca.services; + +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityType; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; + +/** + * The type Tosca util. + */ +public class ToscaUtil { + + /** + * Gets service template file name. + * + * @param serviceTemplate the service template + * @return the service template file name + */ + public static String getServiceTemplateFileName(ServiceTemplate serviceTemplate) { + if (serviceTemplate == null) { + return null; + } + if (serviceTemplate.getMetadata() == null) { + return UUID.randomUUID().toString() + "ServiceTemplate.yaml"; + } + return getServiceTemplateFileName(serviceTemplate.getMetadata().getTemplate_name()); + } + + /** + * Gets service template file name. + * + * @param templateName the template name + * @return the service template file name + */ + public static String getServiceTemplateFileName(String templateName) { + return (Objects.isNull(templateName) ? UUID.randomUUID().toString() : templateName) + + "ServiceTemplate.yaml"; + } + + /** + * Add service template to map with key file name. + * + * @param serviceTemplates the service templates + * @param commonServiceTemplate the common service template + */ + public static void addServiceTemplateToMapWithKeyFileName( + Map<String, ServiceTemplate> serviceTemplates, ServiceTemplate commonServiceTemplate) { + serviceTemplates + .put(ToscaUtil.getServiceTemplateFileName(commonServiceTemplate), commonServiceTemplate); + } + + /** + * Convert type to definition capability definition. + * + * @param type the type + * @param capabilityType the capability type + * @param properties the properties + * @param description the description + * @return the capability definition + */ + public static CapabilityDefinition convertTypeToDefinition(String type, + CapabilityType capabilityType, + Map<String, Object> properties, + String description) { + CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); + capabilityDefinition.setAttributes(capabilityType.getAttributes()); + capabilityDefinition.setProperties(capabilityType.getProperties()); + if (description == null) { + capabilityDefinition.setDescription(capabilityType.getDescription()); + } else { + capabilityDefinition.setDescription(description); + } + capabilityDefinition.setType(type); + + capabilityDefinition.getProperties() + .entrySet() + .stream() + .filter(entry -> properties.containsKey(entry.getKey())) + .forEach(entry -> entry.getValue() + .set_default(properties.get(entry.getKey()))); + + + return capabilityDefinition; + + } + + /** + * Normalize component name node type map. + * + * @param toscaModel the tosca model + * @param components the components + * @return the map + */ + public static Map<String, List<NodeType>> normalizeComponentNameNodeType( + ToscaServiceModel toscaModel, Set<String> components) { + + Map<String, List<NodeType>> normalizedData = new HashMap<>(); + toscaModel + .getServiceTemplates() + .entrySet().stream().filter(entry -> entry + .getValue() + .getNode_types() != null) + .forEach(entry -> entry + .getValue() + .getNode_types() + .entrySet().stream() + .filter(nodeTypeEntry -> components + .contains(nodeTypeEntry + .getKey())) + .forEach(nodeTypeEntry -> addNodeType(nodeTypeEntry.getKey(), nodeTypeEntry.getValue(), + normalizedData))); + return normalizedData; + } + + private static void addNodeType(String key, NodeType value, + Map<String, List<NodeType>> normalizedData) { + if (!normalizedData.containsKey(key)) { + normalizedData.put(key, new ArrayList<>()); + } + normalizedData.get(key).add(value); + } +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java new file mode 100644 index 0000000000..a11bff4b6a --- /dev/null +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java @@ -0,0 +1,467 @@ +/*- + * ============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.tosca.services.impl; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityType; +import org.openecomp.sdc.tosca.datatypes.model.Import; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.errors.ToscaInvalidEntryNotFoundErrorBuilder; +import org.openecomp.sdc.tosca.errors.ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder; +import org.openecomp.sdc.tosca.errors.ToscaInvalidSubstitutionServiceTemplateErrorBuilder; +import org.openecomp.sdc.tosca.errors.ToscaNodeTypeNotFoundErrorBuilder; +import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.tosca.services.yamlutil.ToscaExtensionYamlUtil; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { + /* + node template with type equal to node type or derived from node type. + */ + @Override + public Map<String, NodeTemplate> getNodeTemplatesByType(ServiceTemplate serviceTemplate, + String nodeType, + ToscaServiceModel toscaServiceModel) { + Map<String, NodeTemplate> nodeTemplates = new HashMap<>(); + + if (Objects.nonNull(serviceTemplate.getTopology_template()) + && MapUtils.isNotEmpty(serviceTemplate.getTopology_template().getNode_templates())) { + for (Map.Entry<String, NodeTemplate> nodeTemplateEntry : serviceTemplate + .getTopology_template().getNode_templates().entrySet()) { + if (isTypeOf(nodeTemplateEntry.getValue(), nodeType, serviceTemplate, toscaServiceModel)) { + nodeTemplates.put(nodeTemplateEntry.getKey(), nodeTemplateEntry.getValue()); + } + + } + } + return nodeTemplates; + } + + @Override + public boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType, + ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) { + if (nodeTemplate == null) { + return false; + } + + if (isNodeTemplateOfTypeNodeType(nodeTemplate, nodeType)) { + return true; + } + + Optional<Boolean> nodeTypeExistInServiceTemplateHierarchy = + isNodeTypeExistInServiceTemplateHierarchy(nodeType, nodeTemplate.getType(), serviceTemplate, + toscaServiceModel, null); + return nodeTypeExistInServiceTemplateHierarchy.orElseThrow(() -> new CoreException( + new ToscaNodeTypeNotFoundErrorBuilder(nodeTemplate.getType()).build())); + } + + + private Optional<Boolean> isNodeTypeExistInServiceTemplateHierarchy(String nodeTypeToMatch, + String nodeTypeToSearch, + ServiceTemplate serviceTemplate, + ToscaServiceModel toscaServiceModel, + Set<String> analyzedImportFiles) { + Map<String, NodeType> searchableNodeTypes = serviceTemplate.getNode_types(); + if (!MapUtils.isEmpty(searchableNodeTypes)) { + NodeType nodeType = searchableNodeTypes.get(nodeTypeToSearch); + if (Objects.nonNull(nodeType)) { + if (Objects.equals(nodeType.getDerived_from(), nodeTypeToMatch)) { + return Optional.of(true); + } else if (isNodeTypeIsToscaRoot(nodeType)) { + return Optional.of(false); + } else { + return isNodeTypeExistInServiceTemplateHierarchy(nodeTypeToMatch, + nodeType.getDerived_from(), serviceTemplate, toscaServiceModel, null); + } + } else { + return isNodeTypeExistInImports(nodeTypeToMatch, nodeTypeToSearch, serviceTemplate, + toscaServiceModel, analyzedImportFiles); + } + } + return isNodeTypeExistInImports(nodeTypeToMatch, nodeTypeToSearch, serviceTemplate, + toscaServiceModel, analyzedImportFiles); + + } + + private Optional<Boolean> isNodeTypeExistInImports(String nodeTypeToMatch, + String nodeTypeToSearch, + ServiceTemplate serviceTemplate, + ToscaServiceModel toscaServiceModel, + Set<String> analyzedImportFiles) { + Map<String, Import> imports = serviceTemplate.getImports(); + if (imports == null) { + return Optional.empty(); + } + + analyzedImportFiles = createAnalyzedImportFilesSet(analyzedImportFiles); + for (Import anImport : imports.values()) { + if (Objects.isNull(anImport) || Objects.isNull(anImport.getFile())) { + throw new RuntimeException("import without file entry"); + } + String importFile = anImport.getFile(); + if (analyzedImportFiles.contains(importFile)) { + continue; + } + addImportFileToAnalyzedImportFilesSet(analyzedImportFiles, importFile); + ServiceTemplate template = toscaServiceModel.getServiceTemplates().get(importFile); + Optional<Boolean> nodeTypeExistInServiceTemplateHierarchy = + isNodeTypeExistInServiceTemplateHierarchy(nodeTypeToMatch, nodeTypeToSearch, template, + toscaServiceModel, analyzedImportFiles); + if (nodeTypeExistInServiceTemplateHierarchy.isPresent()) { + if (nodeTypeExistInServiceTemplateHierarchy.get()) { + return Optional.of(true); + } + } + } + return Optional.of(false); + } + + private Set<String> addImportFileToAnalyzedImportFilesSet(Set<String> analyzedImportFiles, + String importFile) { + analyzedImportFiles.add(importFile); + return analyzedImportFiles; + } + + private Set<String> createAnalyzedImportFilesSet(Set<String> analyzedImportFiles) { + if (Objects.isNull(analyzedImportFiles)) { + analyzedImportFiles = new HashSet<>(); + } + return analyzedImportFiles; + } + + private boolean isNodeTypeIsToscaRoot(NodeType stNodeType) { + return Objects.equals(stNodeType.getDerived_from(), ToscaNodeType.ROOT.getDisplayName()); + } + + private boolean isNodeTemplateOfTypeNodeType(NodeTemplate nodeTemplate, String nodeType) { + return Objects.equals(nodeTemplate.getType(), nodeType); + } + + @Override + public List<RequirementAssignment> getRequirements(NodeTemplate nodeTemplate, + String requirementId) { + List<RequirementAssignment> requirements = new ArrayList<>(); + List<Map<String, RequirementAssignment>> requirementList = nodeTemplate.getRequirements(); + if (requirementList != null) { + requirementList.stream().filter(reqMap -> reqMap.get(requirementId) != null) + .forEach(reqMap -> { + ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); + RequirementAssignment reqAssignment = toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqMap.get(requirementId)), + RequirementAssignment.class); + requirements.add(reqAssignment); + }); + } + return requirements; + } + + @Override + public Optional<NodeTemplate> getNodeTemplateById(ServiceTemplate serviceTemplate, + String nodeTemplateId) { + if ((serviceTemplate.getTopology_template() != null) + && (serviceTemplate.getTopology_template().getNode_templates() != null) + && (serviceTemplate.getTopology_template().getNode_templates() + .get(nodeTemplateId) != null)) { + return Optional + .of(serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId)); + } + return Optional.empty(); + } + + @Override + public Optional<String> getSubstituteServiceTemplateName(String substituteNodeTemplateId, + NodeTemplate substitutableNodeTemplate) { + if (!isSubstitutableNodeTemplate(substitutableNodeTemplate)) { + return Optional.empty(); + } + + if (substitutableNodeTemplate.getProperties() != null + && substitutableNodeTemplate.getProperties() + .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME) != null) { + Object serviceTemplateFilter = substitutableNodeTemplate.getProperties() + .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + if (serviceTemplateFilter != null && serviceTemplateFilter instanceof Map) { + Object substituteServiceTemplate = ((Map) serviceTemplateFilter) + .get(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME); + if (substituteServiceTemplate == null) { + throw new CoreException( + new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId) + .build()); + } + return Optional.of(substituteServiceTemplate.toString()); + } + } + throw new CoreException( + new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId) + .build()); + } + + @Override + public Map<String, NodeTemplate> getSubstitutableNodeTemplates(ServiceTemplate serviceTemplate) { + Map<String, NodeTemplate> substitutableNodeTemplates = new HashMap<>(); + + if (serviceTemplate == null + || serviceTemplate.getTopology_template() == null + || serviceTemplate.getTopology_template().getNode_templates() == null) { + return substitutableNodeTemplates; + } + + Map<String, NodeTemplate> nodeTemplates = + serviceTemplate.getTopology_template().getNode_templates(); + for (String nodeTemplateId : nodeTemplates.keySet()) { + NodeTemplate nodeTemplate = nodeTemplates.get(nodeTemplateId); + if (isSubstitutableNodeTemplate(nodeTemplate)) { + substitutableNodeTemplates.put(nodeTemplateId, nodeTemplate); + } + } + + return substitutableNodeTemplates; + } + + private boolean isSubstitutableNodeTemplate(NodeTemplate nodeTemplate) { + return nodeTemplate.getDirectives() != null + && nodeTemplate.getDirectives().contains(ToscaConstants + .NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); + } + + private boolean isSubstitutionServiceTemplate(String substituteServiceTemplateFileName, + ServiceTemplate substituteServiceTemplate) { + if (substituteServiceTemplate != null + && substituteServiceTemplate.getTopology_template() != null + && substituteServiceTemplate.getTopology_template().getSubstitution_mappings() != null) { + if (substituteServiceTemplate.getTopology_template().getSubstitution_mappings() + .getNode_type() == null) { + throw new CoreException(new ToscaInvalidSubstitutionServiceTemplateErrorBuilder( + substituteServiceTemplateFileName).build()); + } + return true; + } + return false; + + } + + @Override + public Optional<Map.Entry<String, NodeTemplate>> getSubstitutionMappedNodeTemplateByExposedReq( + String substituteServiceTemplateFileName, ServiceTemplate substituteServiceTemplate, + String requirementId) { + if (isSubstitutionServiceTemplate(substituteServiceTemplateFileName, + substituteServiceTemplate)) { + Map<String, List<String>> substitutionMappingRequirements = + substituteServiceTemplate.getTopology_template().getSubstitution_mappings() + .getRequirements(); + if (substitutionMappingRequirements != null) { + List<String> requirementMapping = substitutionMappingRequirements.get(requirementId); + if (requirementMapping != null && !requirementMapping.isEmpty()) { + String mappedNodeTemplateId = requirementMapping.get(0); + Optional<NodeTemplate> mappedNodeTemplate = + getNodeTemplateById(substituteServiceTemplate, mappedNodeTemplateId); + mappedNodeTemplate.orElseThrow(() -> new CoreException( + new ToscaInvalidEntryNotFoundErrorBuilder("Node Template", mappedNodeTemplateId) + .build())); + Map.Entry<String, NodeTemplate> mappedNodeTemplateEntry = + new Map.Entry<String, NodeTemplate>() { + @Override + public String getKey() { + return mappedNodeTemplateId; + } + + @Override + public NodeTemplate getValue() { + return mappedNodeTemplate.get(); + } + + @Override + public NodeTemplate setValue(NodeTemplate value) { + return null; + } + }; + return Optional.of(mappedNodeTemplateEntry); + } + } + } + return Optional.empty(); + } + + + /* + match only for the input which is not null + */ + @Override + public boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment, + String capability, String node, + String relationship) { + if (capability != null) { + if (requirementAssignment.getCapability() == null + || !requirementAssignment.getCapability().equals(capability)) { + return false; + } + } + + if (node != null) { + if (requirementAssignment.getNode() == null + || !requirementAssignment.getNode().equals(node)) { + return false; + } + } + + if (relationship != null) { + if (requirementAssignment.getRelationship() == null + || !requirementAssignment.getRelationship().equals(relationship)) { + return false; + } + } + + return !(capability == null && node == null && relationship == null); + + } + + @Override + public Object getFlatEntity(ToscaElementTypes elementType, String typeId, + ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel) { + Object returnEntity; + + switch (elementType) { + case CAPABILITY_TYPE: + returnEntity = new CapabilityType(); + break; + default: + throw new RuntimeException( + "Entity[" + elementType + "] id[" + typeId + "] flat not supported"); + } + + scanAnFlatEntity(elementType, typeId, returnEntity, serviceTemplate, toscaModel); + + + return returnEntity; + } + + private void scanAnFlatEntity(ToscaElementTypes elementType, String typeId, Object entity, + ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel) { + + + boolean entityFound = + enrichEntityFromCurrentServiceTemplate(elementType, typeId, entity, serviceTemplate, + toscaModel); + if (!entityFound) { + Map<String, Import> imports = serviceTemplate.getImports(); + if (MapUtils.isEmpty(imports)) { + return; + } + for (Import importServiceTemplate : imports.values()) { + ServiceTemplate template = + toscaModel.getServiceTemplates().get(importServiceTemplate.getFile()); + scanAnFlatEntity(elementType, typeId, entity, template, toscaModel); + } + } + + + } + + private boolean enrichEntityFromCurrentServiceTemplate(ToscaElementTypes elementType, + String typeId, Object entity, + ServiceTemplate serviceTemplate, + ToscaServiceModel toscaModel) { + String derivedFrom; + switch (elementType) { + case CAPABILITY_TYPE: + if (serviceTemplate.getCapability_types() != null + && serviceTemplate.getCapability_types().containsKey(typeId)) { + + CapabilityType targetCapabilityType = ((CapabilityType) entity); + CapabilityType sourceCapabilityType = serviceTemplate.getCapability_types().get(typeId); + derivedFrom = sourceCapabilityType.getDerived_from(); + if (derivedFrom != null + && !ToscaCapabilityType.NFV_METRIC.getDisplayName().equals(derivedFrom)) { + scanAnFlatEntity(elementType, derivedFrom, entity, serviceTemplate, toscaModel); + } + combineCapabilityTypeInfo(sourceCapabilityType, targetCapabilityType); + } else { + return false; + } + break; + default: + throw new RuntimeException( + "Entity[" + elementType + "] id[" + typeId + "] flat not supported"); + } + + return true; + + + } + + private void combineCapabilityTypeInfo(CapabilityType sourceCapabilityType, + CapabilityType targetCapabilityType) { + if (MapUtils.isNotEmpty(sourceCapabilityType.getAttributes())) { + if (targetCapabilityType.getAttributes() == null) { + targetCapabilityType.setAttributes(new HashMap<>()); + } + targetCapabilityType.getAttributes().putAll(sourceCapabilityType.getAttributes()); + } + + if (MapUtils.isNotEmpty(sourceCapabilityType.getProperties())) { + if (targetCapabilityType.getProperties() == null) { + targetCapabilityType.setProperties(new HashMap<>()); + } + targetCapabilityType.getProperties().putAll(sourceCapabilityType.getProperties()); + } + + if (CollectionUtils.isNotEmpty(sourceCapabilityType.getValid_source_types())) { + if (targetCapabilityType.getValid_source_types() == null) { + targetCapabilityType.setValid_source_types(new ArrayList<>()); + } + targetCapabilityType.getValid_source_types() + .addAll(sourceCapabilityType.getValid_source_types()); + } + + if (CommonMethods.isEmpty(sourceCapabilityType.getDerived_from())) { + targetCapabilityType.setDerived_from(sourceCapabilityType.getDerived_from()); + } + if (CommonMethods.isEmpty(sourceCapabilityType.getDescription())) { + targetCapabilityType.setDescription(sourceCapabilityType.getDescription()); + } + if (CommonMethods.isEmpty(sourceCapabilityType.getVersion())) { + targetCapabilityType.setVersion(sourceCapabilityType.getVersion()); + } + + + } + + +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImpl.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImpl.java new file mode 100644 index 0000000000..d4c22f105f --- /dev/null +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImpl.java @@ -0,0 +1,158 @@ +/*- + * ============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.tosca.services.impl; + +import org.openecomp.core.utilities.file.FileContentHandler; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.exceptions.CsarCreationErrorBuilder; +import org.openecomp.sdc.tosca.exceptions.CsarMissingEntryPointErrorBuilder; +import org.openecomp.sdc.tosca.services.ToscaFileOutputService; + +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +public class ToscaFileOutputServiceCsarImpl implements ToscaFileOutputService { + static final String EXTERNAL_ARTIFACTS_FOLDER_NAME = "Artifacts"; + private static final String DEFINITIONS_FOLDER_NAME = "Definitions"; + private static final String ARTIFACTS_FOLDER_NAME = "Artifacts"; + //todo currently duplicated, to be changed when external artifacts are separated from internal + private static final String TOSCA_META_FOLDER_NAME = "TOSCA-Metadata"; + private static final String TOSCA_META_FILE_VERSION = "TOSCA-Meta-File-Version"; + private static final String TOSCA_META_FILE_VERSION_VALUE = "1.0"; + private static final String TOSCA_META_FILE_NAME = "TOSCA.meta"; + private static final String CSAR_VERSION = "CSAR-Version"; + private static final String CSAR_VERSION_VALUE = "1.1"; + private static final String CREATED_BY = "Created-By"; + private static final String CREATED_BY_VALUE = "ASDC Onboarding portal"; + private static final String ENTRY_DEFINITIONS = "Entry-Definitions"; + private static final String META_FILE_DELIMITER = ":"; + private static final String SPACE = " "; + private static final String FILE_SEPARATOR = File.separator; + + @Override + public byte[] createOutputFile(ToscaServiceModel toscaServiceModel, + FileContentHandler externalArtifacts) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos))) { + packDefinitions(zos, toscaServiceModel.getServiceTemplates()); + FileContentHandler artifactFiles = toscaServiceModel.getArtifactFiles(); + if (artifactFiles != null && !artifactFiles.isEmpty()) { + packArtifacts(zos, artifactFiles); + } + if (toscaServiceModel.getEntryDefinitionServiceTemplate() == null) { + throw new CoreException(new CsarMissingEntryPointErrorBuilder().build()); + } + createAndPackToscaMetaFile(zos, toscaServiceModel.getEntryDefinitionServiceTemplate()); + if (externalArtifacts != null) { + packExternalArtifacts(zos, externalArtifacts); + } + } catch (IOException exc) { + throw new CoreException(new CsarCreationErrorBuilder().build(), exc); + } + return baos.toByteArray(); + } + + @Override + public String createMetaFile(String entryDefinitionsFileName) { + return TOSCA_META_FILE_VERSION + META_FILE_DELIMITER + SPACE + TOSCA_META_FILE_VERSION_VALUE + + System.lineSeparator() + + CSAR_VERSION + META_FILE_DELIMITER + SPACE + CSAR_VERSION_VALUE + System.lineSeparator() + + CREATED_BY + META_FILE_DELIMITER + SPACE + CREATED_BY_VALUE + System.lineSeparator() + + ENTRY_DEFINITIONS + META_FILE_DELIMITER + SPACE + DEFINITIONS_FOLDER_NAME + + FILE_SEPARATOR + entryDefinitionsFileName; + } + + @Override + public String getArtifactsFolderName() { + return ARTIFACTS_FOLDER_NAME; + } + + private void createAndPackToscaMetaFile(ZipOutputStream zos, String entryDefinitionsFileName) + throws IOException { + String metaFile = createMetaFile(entryDefinitionsFileName); + zos.putNextEntry( + new ZipEntry((TOSCA_META_FOLDER_NAME + FILE_SEPARATOR + TOSCA_META_FILE_NAME))); + writeBytesToZip(zos, new ByteArrayInputStream(metaFile.getBytes())); + } + + private void packDefinitions(ZipOutputStream zos, Map<String, ServiceTemplate> serviceTemplates) + throws IOException { + for (Map.Entry<String, ServiceTemplate> serviceTemplate : serviceTemplates.entrySet()) { + String fileName = serviceTemplate.getKey(); + zos.putNextEntry(new ZipEntry(DEFINITIONS_FOLDER_NAME + FILE_SEPARATOR + fileName)); + writeBytesToZip(zos, + FileUtils.convertToInputStream(serviceTemplate.getValue(), FileUtils.FileExtension.YAML)); + } + } + + private void packExternalArtifacts(ZipOutputStream zos, FileContentHandler externalArtifacts) { + + for (String filenameIncludingPath : externalArtifacts.getFileList()) { + try { + zos.putNextEntry(new ZipEntry(filenameIncludingPath)); + writeBytesToZip(zos, externalArtifacts.getFileContent(filenameIncludingPath)); + + } catch (IOException exc) { + throw new RuntimeException(exc); + } finally { + try { + zos.closeEntry(); + } catch (IOException ignore) { + //do nothing + } + } + } + + } + + private void packArtifacts(ZipOutputStream zos, FileContentHandler artifacts) { + + for (String fileName : artifacts.getFileList()) { + try { + zos.putNextEntry(new ZipEntry((ARTIFACTS_FOLDER_NAME + FILE_SEPARATOR + fileName))); + writeBytesToZip(zos, artifacts.getFileContent(fileName)); + + } catch (IOException exc) { + throw new RuntimeException(exc); + } finally { + try { + zos.closeEntry(); + } catch (IOException ignore) { + //do nothing + } + } + } + } + + private void writeBytesToZip(ZipOutputStream zos, InputStream is) throws IOException { + FileUtils.copy(is, zos); + } +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/yamlutil/ToscaExtensionYamlUtil.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/yamlutil/ToscaExtensionYamlUtil.java new file mode 100644 index 0000000000..a1c11c2483 --- /dev/null +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/yamlutil/ToscaExtensionYamlUtil.java @@ -0,0 +1,93 @@ +/*- + * ============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.tosca.services.yamlutil; + +import org.openecomp.core.utilities.yaml.YamlUtil; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.introspector.PropertyUtils; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.NodeId; + +import java.beans.IntrospectionException; + +public class ToscaExtensionYamlUtil extends YamlUtil { + + @Override + public <T> Constructor getConstructor(Class<T> typClass) { + return new ToscaWithHeatExtensionConstructor(typClass); + } + + @Override + protected PropertyUtils getPropertyUtils() { + return new ToscaPropertyUtilsWithHeatExtension(); + } + + public class ToscaPropertyUtilsWithHeatExtension extends MyPropertyUtils { + @Override + public Property getProperty(Class<? extends Object> type, String name) + throws IntrospectionException { + try { + if (type.equals( + Class.forName("org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition"))) { + type = Class.forName( + "org.openecomp.sdc.tosca.datatypes.model.heatextend.ParameterDefinitionExt"); + } + } catch (ClassNotFoundException exception) { + throw new RuntimeException(exception); + } + return super.getProperty(type, name); + } + } + + protected class ToscaWithHeatExtensionConstructor extends StrictMapAppenderConstructor { + public ToscaWithHeatExtensionConstructor(Class<?> theRoot) { + super(theRoot); + yamlClassConstructors.put(NodeId.mapping, new MyPersistentObjectConstruct()); + } + + class MyPersistentObjectConstruct extends ConstructMapping { + @Override + protected Object constructJavaBean2ndStep(MappingNode node, Object object) { + Class type = node.getType(); + try { + if (type.equals( + Class.forName("org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition"))) { + Class extendHeatClass = Class.forName( + "org.openecomp.sdc.tosca.datatypes.model.heatextend.ParameterDefinitionExt"); + Object extendHeatObject = extendHeatClass.newInstance(); + // create JavaBean + return super.constructJavaBean2ndStep(node, extendHeatObject); + } else { + // create JavaBean + return super.constructJavaBean2ndStep(node, object); + } + } catch (ClassNotFoundException | InstantiationException + | IllegalAccessException exception) { + throw new RuntimeException(exception); + } + } + } + } +} + + + |