diff options
Diffstat (limited to 'sdc-tosca/src/main/java')
36 files changed, 4758 insertions, 0 deletions
diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/ConformanceLevel.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/ConformanceLevel.java new file mode 100644 index 0000000..4124690 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/ConformanceLevel.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.api; + +public class ConformanceLevel { + + private String minVersion; + private String maxVersion; + + public String getMaxVersion() { + return maxVersion; + } + + public void setMaxVersion(String maxVersion) { + this.maxVersion = maxVersion; + } + + public String getMinVersion() { + return minVersion; + } + + public void setMinVersion(String minVersion) { + this.minVersion = minVersion; + } + + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/IEntityDetails.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/IEntityDetails.java new file mode 100644 index 0000000..b69a8b3 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/IEntityDetails.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.api; + +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.toscaparser.api.CapabilityAssignment; +import org.onap.sdc.toscaparser.api.Property; +import org.onap.sdc.toscaparser.api.RequirementAssignment; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.sdc.toscaparser.api.parameters.Input; + +import java.util.List; +import java.util.Map; + +public interface IEntityDetails { + /** + * Retrieves entity instance template type. + * @return {@link EntityTemplateType} enum entry describing given object type + */ + EntityTemplateType getEntityType(); + + /** + * Retrieves entity instance name + */ + String getName(); + + /** + * Retrieves entity Tosca type + */ + String getToscaType(); + + /** + * Retrieves entity {@link Metadata} object + */ + Metadata getMetadata(); + + /** + * Retrieves entity instance properties + * @return map of entity property names and corresponding {@link Property} object instances + */ + Map<String, Property> getProperties(); + + /** + * Retrieves member names of the entity instance + * @return List of member names + */ + List<String> getMembers(); + + /** + * Retrieves member nodes of the entity instance + * @return List of member nodes entity objects + */ + List<IEntityDetails> getMemberNodes(); + + /** + * Retrieves node template containing the current entity instance. + * @return parent entity instance or null if the entity is contained by service + */ + IEntityDetails getParent(); + + /** + * Retrieves path to the searched entity instance in the model. It is based on the collection of the node templates names delimited by #. + * The entity instance may exist in the service node templates, in the VF node templates or in the nested of nested CVFC. + * The path will include the VF name, then the names of the CVFC recursively. + * If the entity instance is located in the service directly, the path is empty string + */ + String getPath(); + + /** + * Retrieves map of requirements of the entity instance + * @return map of entity requirement names and corresponding {@link RequirementAssignment} object instances + */ + List<RequirementAssignment> getRequirements(); + + /** + * Retrieves map of capabilities of the entity instance + * @return map of entity capability names and corresponding {@link CapabilityAssignment} object instances + */ + List<CapabilityAssignment> getCapabilities(); + + /** + * Retrieves list of policy target names + */ + List<String> getTargets(); + + /** + * Retrieves list of policy target entity instances (groups or node templates) + */ + List<IEntityDetails> getTargetEntities(); + + /** + * Retrieves list of inputs + */ + List<Input> getInputs(); +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/ISdcCsarHelper.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/ISdcCsarHelper.java new file mode 100644 index 0000000..e4e8f3c --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/ISdcCsarHelper.java @@ -0,0 +1,681 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.sdc.tosca.parser.api; + + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang3.tuple.Pair; +import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery; +import org.onap.sdc.tosca.parser.elements.queries.EntityQuery; +import org.onap.sdc.tosca.parser.enums.SdcTypes; +import org.onap.sdc.tosca.parser.enums.FilterType; +import org.onap.sdc.toscaparser.api.*; +import org.onap.sdc.toscaparser.api.elements.DataType; +import org.onap.sdc.toscaparser.api.elements.InterfacesDef; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.sdc.toscaparser.api.parameters.Input; + + +public interface ISdcCsarHelper { + + /** + * Get all node templates by node_type for this CSAR service. + * + * @param nodeType - the TOSCA type of the node. + * @return service node templates of this type. + */ + @Deprecated + public List<NodeTemplate> getServiceNodeTemplatesByType(String nodeType); + + /** + * Get all node templates for this CSAR service. + * + * @return service node templates. + */ + @Deprecated + public List<NodeTemplate> getServiceNodeTemplates(); + + /** + * Get groups of a VF with type "org.onap.groups.VfModule". + * + * @param vfCustomizationUuid - customizationUuid of VF instance. + * @return list of vfModule groups. + */ + @Deprecated + public List<Group> getVfModulesByVf(String vfCustomizationUuid); + + + /** + * Get any property leaf value for node template by full path separated by #.<br> + * For example, for node template with this property:<br><br> + * network_assignments:<br> + ecomp_generated_network_assignment: true<br> + is_shared_network: false<br> + is_external_network: false<br> + ipv4_subnet_default_assignments:<br> + use_ipv4: true<br> + ip_network_address_plan: 1.2.3.4<br> + dhcp_enabled: true<br> + ip_version: 4<br> + cidr_mask: 24<br> + min_subnets_count: 1<br> + ipv6_subnet_default_assignments:<br> + use_ipv6: false<br><br> + + * calling<br> + * getNodeTemplatePropertyLeafValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignments#use_ipv6")<br> + * will return "false". + * @param nodeTemplate - nodeTemplate where the property should be looked up. + * @param pathToPropertyLeafValue - the full path of the required property. + * @return the leaf value as String, or null if there's no such property, or it's not a leaf. + */ + @Deprecated + public String getNodeTemplatePropertyLeafValue(NodeTemplate nodeTemplate, String pathToPropertyLeafValue); + + /** + * Get any property leaf value for node template by full path separated by #.<br> + * For example, for node template with this property:<br><br> + * network_assignments:<br> + ecomp_generated_network_assignment: true<br> + is_shared_network: false<br> + is_external_network: false<br> + ipv4_subnet_default_assignments:<br> + use_ipv4: true<br> + ip_network_address_plan: 1.2.3.4<br> + dhcp_enabled: true<br> + ip_version: 4<br> + cidr_mask: 24<br> + min_subnets_count: 1<br> + ipv6_subnet_default_assignments:<br> + use_ipv6: false<br><br> + + * calling<br> + * getNodeTemplatePropertyLeafValue(nodeTemplate, "network_assignments#ipv6_subnet_default_assignments#use_ipv6")<br> + * will return "false". + * @param nodeTemplate - nodeTemplate where the property should be looked up. + * @param pathToPropertyLeafValue - the full path of the required property. + * @return the leaf value as Object, or null if there's no such property. It's up to the caller to cast it to a proper type. + */ + @Deprecated + public Object getNodeTemplatePropertyValueAsObject(NodeTemplate nodeTemplate, String pathToPropertyLeafValue); + + /** + * Get any property leaf value for a group definition by full path separated by #. + * Same logic as in {@link #getNodeTemplatePropertyLeafValue(NodeTemplate, String) getNodeTemplatePropertyLeafValue}, only for a group. + * @param group - group where the property should be looked up. + * @param propertyName - the name of the required property. + * @return the leaf value as String, or null if there's no such property, or it's not a leaf. + */ + @Deprecated + public String getGroupPropertyLeafValue(Group group, String propertyName); + + /** + * Get any property value for a group definition by full path separated by #. + * Same logic as in {@link #getNodeTemplatePropertyLeafValue(NodeTemplate, String) getNodeTemplatePropertyLeafValue}, only for a group. + * @param group - group where the property should be looked up. + * @param propertyName - the name of the required property. + * @return the leaf value as Object, or null if there's no such property. It's up to the caller to cast it to a proper type. + */ + @Deprecated + public Object getGroupPropertyAsObject(Group group, String propertyName); + + /** + * Get all VL node templates of the CSAR service. + * @return - all VL node templates. + */ + @Deprecated + public List<NodeTemplate> getServiceVlList(); + + /** + * Get all VF node templates of the CSAR service. + * @return - all VF node templates. + */ + @Deprecated + public List<NodeTemplate> getServiceVfList(); + + + /** + * + * Get a property from a metadata object.<br> + * This is just sugaring method, same as calling metadata.getMetadataPropertyValue(metadataPropertyName).<br> + * + * For metadata object representing the below: <br><br> + * + * metadata:<br> + invariantUUID: 4598a404-00e1-42a6-8767-0bda343e2066<br> + UUID: e17940d6-42f8-4989-bad0-31de5addc619<br> + customizationUUID: 83d086b2-a861-4d3b-aa84-3bfbb9b2ec20<br> + version: '0.1'<br> + name: vIPR_ATM<br> + description: vIPR_ATM<br> + type: VF<br> + category: category1<br> + subcategory: subCategory1<br><br> + + calling<br> + getMetadataPropertyValue(metadata,"invariantUUID")<br> + will return "4598a404-00e1-42a6-8767-0bda343e2066". + + * @param metadata - metadata object. + * @param metadataPropertyName - the name of the metadata property. + * @return metadata property value + */ + @Deprecated + public String getMetadataPropertyValue(Metadata metadata, String metadataPropertyName); + + + /** + * Get input leaf value for the CSAR service, by full path separated by #.<br> + * Same logic as in {@link #getNodeTemplatePropertyLeafValue(NodeTemplate, String) getNodeTemplatePropertyLeafValue}, only for an input full path. + * The expected format is "input_name#default[optionally #rest_of_path]" + * @param inputLeafValuePath by full path separated by #. + * @return input leaf value for the service. + */ + public String getServiceInputLeafValueOfDefault(String inputLeafValuePath); + + /** + * Get input leaf value for the CSAR service, by full path separated by #.<br> + * Same logic as in {@link #getNodeTemplatePropertyLeafValue(NodeTemplate, String) getNodeTemplatePropertyLeafValue}, only for an input full path. + * The expected format is "input_name#default[optionally #rest_of_path]" + * @param inputLeafValuePath by full path separated by #. + * @return input value for the service as Object. It's up to the caller to cast it to a proper type. + */ + public Object getServiceInputLeafValueOfDefaultAsObject(String inputLeafValuePath); + + /** + * Get the type name of the CSAR service's substitution mappings element.<br> + * + * For the below:<br><br> + * + * substitution_mappings:<br> + type: org.onap.services.ViprATM<br> + + calling<br> + getServiceSubstitutionMappingsTypeName()<br> + will return "org.onap.services.ViprATM" + * @return - the type name of the CSAR service's substitution mappings element + */ + public String getServiceSubstitutionMappingsTypeName(); + + /** + * Get service Metadata object.<br> + * This object represents the "metadata" section of a CSAR service. + * @return - the service Metadata object. + */ + public Metadata getServiceMetadata(); + + /** + * Get the CSAR service metadata as map. + * @return - the service metadata object as Map. + * @deprecated This function is deprecated since its not tosca compliant. <br> + * Tosca defines the Metadata section as map of string (not map of object).<br> + * This function is targeted to be removed as part of 1802.<br> + * Please use {@link #getServiceMetadataAllProperties() getServiceMetadataAllProperties()}. + */ + @Deprecated + public Map<String, Object> getServiceMetadataProperties(); + + /** + * Get the CSAR service metadata as map + * @return - the service metadata object as Map + */ + public Map<String, String> getServiceMetadataAllProperties(); + + /** + * Get all VFC node templates from a specified VF. + * @param vfCustomizationId - customizationUuid of the VF node template. + * @return all VFC node templates from a specified VF + */ + @Deprecated + public List<NodeTemplate> getVfcListByVf(String vfCustomizationId); + + /** + * Get all CP node templates from a specified VF. + * @param vfCustomizationId - customizationUuid of the VF node template. + * @return all CP node templates from a specified VF + */ + @Deprecated + public List<NodeTemplate> getCpListByVf(String vfCustomizationId); + + /** + * Get all members of this group definition.<br> + * + * For example, for this group definition:<br><br> + * + * ViprAtm..vIPR-ATM-Base..module-0:<br> + type: org.onap.groups.VfModule<br> + .................<br> + members: [vIPR_ATM_Ha_Two, vIPR_ATM_Ha_One, vIPR_ATM_OAM_SG, vIPR_ATM_HA_TWO_SG, vIPR_ATM_HA_ONE_SG]<br><br> + + calling<br> + getMembersOfVfModule(NoteTemplate vfNodeTemplate, Group group)<br> + will return List of the following Node templates in the vfNodeTemplate: "vIPR_ATM_Ha_Two, vIPR_ATM_Ha_One, vIPR_ATM_OAM_SG, vIPR_ATM_HA_TWO_SG, vIPR_ATM_HA_ONE_SG"<br> + * @param vf - VF to return the node templates from. + * @param vfModule - group to return the members from. + * @return node templates from vf with the names as in members section. + * + */ + @Deprecated + public List<NodeTemplate> getMembersOfVfModule(NodeTemplate vf, Group vfModule); + + + /** + * Get list of node template pairs, where for each pair,<br> + * the left node template in pair has requirement with name reqName, <br> + * which should be satisfied with respective capability by the right node template in pair.<br> + * + * For example, if we have the below two node templates in the vIPR VF:<br><br> + * + * oam_extCP:<br> + type: org.onap.resources.cp.extCP<br> + requirements:<br> + - virtualBinding: vipr_atm_firewall<br><br> + * + * vipr_atm_firewall: <br> + type: org.onap.resources.vfc.ViprAtm.abstract.nodes.heat.vipr_atm<br> + ........<br><br> + * + + * calling<br> + * getNodeTemplatePairsByReqName(getCpListByVf(viprCustomUuid), getVfcListByVf(viprCustomUuid), "virtualBinding")<br> + * will return a list with one Pair - where left element of pair will be "oam_extCP" node template,<br> + * and right element will be "vipr_atm_firewall" node template.<br> + * + * @param listOfReqNodeTemplates - list of node templates in which the "reqName" requirement should be looked. + * @param listOfCapNodeTemplates - list of node templates in which the capability matching the "reqName" requirement should be looked. + * @param reqName - the name of a requirement definition to match by. + * @return pairs of node templates according to described above. + */ + public List<Pair<NodeTemplate,NodeTemplate>> getNodeTemplatePairsByReqName(List<NodeTemplate> listOfReqNodeTemplates, List<NodeTemplate> listOfCapNodeTemplates, String reqName); + + /** + * Get all allotted node templates from this service. + * @return all allotted node templates from this service. + */ + @Deprecated + public List<NodeTemplate> getAllottedResources(); + + /** + * Get node_type of a node template.<br> + * + * For this node template:<br> + * + * vipr_atm_firewall: <br> + type: org.onap.resources.vfc.ViprAtm.abstract.nodes.heat.vipr_atm<br> + ........<br><br> + * + * the function will return "org.onap.resources.vfc.ViprAtm.abstract.nodes.heat.vipr_atm" + * + * @param nodeTemplate - node template object + * @return - node type string. + */ + @Deprecated + public String getTypeOfNodeTemplate(NodeTemplate nodeTemplate); + + /** + * Get the CSAR service inputs list. + * @return - the service inputs list. + */ + public List<Input> getServiceInputs(); + + + /** + * Get the conformance level of this CSAR. <br> + * The conformance level value of the CSAR is located in csar.meta file at the top level of the CSAR file.<br> + * For 1707 CSARs, the conformance level is 3.0. + * @return the conformance level of the CSAR. + */ + public String getConformanceLevel(); + + + /** + * Get the map of CP-related props from a VFC node template. <br> + * Let's say there are 5 CPs related to this VFC. Then the output will look like this: <br><br> + * {port_fe1_sigtran={ip_requirements#ip_count_required#count=1, ip_requirements#dhcp_enabled=true, ip_requirements#ip_version=4, subnetpoolid="subnet_1", network_role_tag="SIGNET_vrf_B1_direct"},<br> + * port_fe_cluster={ip_requirements#ip_count_required#count=2, ip_requirements#dhcp_enabled=true, ip_requirements#ip_version=4},<br> + * port_fe_slan={ip_requirements#ip_count_required#count=1, ip_requirements#dhcp_enabled=true, ip_requirements#ip_version=4},<br> + * port_fe_interce={ip_requirements#ip_count_required#count=1, ip_requirements#dhcp_enabled=true, ip_requirements#ip_version=4},<br> + * port_fe_oam={ip_requirements#ip_count_required#count=2, ip_requirements#dhcp_enabled=true, ip_requirements#ip_version=4, subnetpoolid="subnet_2", network_role_tag="Mobility_OAM_protected"}}<br><br> + * @param vfc - VFC node template to look for CP-related props. + * @return map <b>CP node template name</b> to a map of <b>full path to a property on this CP</b> - <b> value of this property on this CP</b>. + * @deprecated This function is deprecated since its flattened form doesn't provide solution for cp properties of type List. + * Will be removed in 1802. + */ + @Deprecated + public Map<String, Map<String, Object>> getCpPropertiesFromVfc(NodeTemplate vfc); + + /** + * Get the map of CP-related props from a VFC node template. <br> + * Let's say there are 2 CPs (ports) related to this VFC. Then the output will look like this: <br><br> + * {port_fe_sigtran={ip_requirements={ip_count_required: {count: 1}, dhcp_enabled: true, ip_version: 4}, subnetpoolid: "subnet_1", network_role_tag: "SIGNET_vrf_B1_direct"}<br> + * port_fe_cluster={ip_requirements={ip_count_required: {count: 2}, dhcp_enabled: true, ip_version: 4}}<br> + * @param vfc - VFC node template to look for CP-related props. + * @return map <b>CP node template name</b> to a map of <b>property name</b> - <b> property value as object</b>. + */ + @Deprecated + public Map<String, Map<String, Object>> getCpPropertiesFromVfcAsObject(NodeTemplate vfc); + + /** + * Get customization UUID of a node template + * @param nt - node template + * @return customization UUID of a node template. + */ + @Deprecated + public String getNodeTemplateCustomizationUuid(NodeTemplate nt); + + /** + * Filter Node Template property values by equals/contains operator and a pattern + * @param nodeTemplate Node Template to filter its properties + * @param filterType filter type - equals or contains + * @param pattern value to filter with it + * @return Map <b>full path to a property</b> mapped to <b>property value</b> filtered by type and pattern + */ + public Map<String, String> filterNodeTemplatePropertiesByValue(NodeTemplate nodeTemplate, FilterType filterType, String pattern); + + /** + * Get all node templates by sdcType for parent Node Template. + * + * @param parentNodeTemplate - parent node template + * @param sdcType - the SDC type of the node. + * @return node templates of this SDC type. + */ + @Deprecated + public List<NodeTemplate> getNodeTemplateBySdcType(NodeTemplate parentNodeTemplate, SdcTypes sdcType); + + /** + * Get all node templates by SDC type enum for this CSAR service. + * + * @param sdcType - the SDC type of the node (for example, CP, VF...). + * @return service node templates of this SDC type. + */ + @Deprecated + public List<NodeTemplate> getServiceNodeTemplateBySdcType(SdcTypes sdcType); + + /** + * Get all node templates for this CSAR service. + * @param vfCustomizationUuid - the Customization UUID of the node. + * @return VNF Configuration Node Template. + */ + @Deprecated + public NodeTemplate getVnfConfig(String vfCustomizationUuid); + + /** + * Check if Node Template has Topology Template + * @param nodeTemplate - Node Template to check + * @return true if node template has topology template, false if not. + */ + @Deprecated + public boolean hasTopology(NodeTemplate nodeTemplate); + + /** + * Get children node templates for node template. + * @param nodeTemplate - Node Template to get its children + * @return return list of children node templates for node template. + */ + @Deprecated + public List<NodeTemplate> getNodeTemplateChildren(NodeTemplate nodeTemplate); + + /** + * Get node template on service level by node template name. + * @param nodeName - the name of the node template. + * @return service-level node template with this name, or null if no such node template was found. + */ + @Deprecated + public NodeTemplate getServiceNodeTemplateByNodeName(String nodeName); + + /** + * Get node template Metadata object.<br> + * This object represents the "metadata" section of node template. + * @param nt - Node template to get its Metadata object. + * @return Metadata for this node template, or null if not found. + */ + @Deprecated + public Metadata getNodeTemplateMetadata(NodeTemplate nt); + + /** + * Get CapabilityAssignments object for this node template.<br> + * This should be an entry point function for working with capability assignments of node template.<br> + * This object allows filtering capability assignments objects.<br> + * @param nt - Node Template to get its capability assignments. + * @return CapabilitiesAssignments that contains list of capability assignments for the node template.<br> + * If none found, an empty list will be returned. + */ + @Deprecated + public CapabilityAssignments getCapabilitiesOf(NodeTemplate nt); + + /** + * Get RequirementAssignments object for this node template.<br> + * This should be an entry point function for working with requirement assignments of node template.<br> + * This object allows filtering requirement assignments objects.<br> + * @param nt - Node Template to get its requirement assignments. + * @return RequirementAssignments that contains list of requirement assignments for the node template. + * If none found, an empty list will be returned. + */ + @Deprecated + public RequirementAssignments getRequirementsOf(NodeTemplate nt); + + /** + * Get any property leaf value for capability by full path separated by #. + * Same logic as in {@link #getNodeTemplatePropertyLeafValue(NodeTemplate, String) getNodeTemplatePropertyLeafValue}, only for a capability assignment. + * @param capability - capability assignment where the property should be looked up. + * @param pathToPropertyLeafValue - the full path of the required property. + * @return the leaf value as String, or null if there's no such property, or it's not a leaf. + */ + @Deprecated + public String getCapabilityPropertyLeafValue(CapabilityAssignment capability, String pathToPropertyLeafValue); + + /** + * Get all the policies of the main topology template (either VF or service) + * @return the list of the policies + */ + @Deprecated + public List<Policy> getPoliciesOfTopologyTemplate(); + + /** + * Get all the policies of the main topology template (either VF or service) specified by policy type + * @param policyTypeName the name of the policy type + * @return the list of the policies + */ + @Deprecated + public List<Policy> getPoliciesOfTopologyTemplateByToscaPolicyType(String policyTypeName); + + /** + * Get all the policies of the origin component (nested topology template) of the node template + * @param nodeTemplate the node template + * @return the list of the policies + */ + @Deprecated + public List<Policy> getPoliciesOfOriginOfNodeTemplate(NodeTemplate nodeTemplate); + + /** + * Get all the policies of the origin component (nested topology template) of the node template specified by policy type + * @param nodeTemplate the node template + * @param policyTypeName the name of the policy type + * @return the list of the policies + */ + @Deprecated + List<Policy> getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(NodeTemplate nodeTemplate, String policyTypeName); + + /** + * Get all the node templates of the topology template, which are the targets of the policy specified by name + * @param policyName the name of the policy + * @return the list of the node templates + */ + @Deprecated + List<NodeTemplate> getPolicyTargetsFromTopologyTemplate(String policyName); + + /** + * Get all the node templates of the origin component (nested topology template) of node template, which are the targets of the policy specified by name + * @param nodeTemplate the node template + * @param policyName the name of the policy + * @return the list of the node templates + */ + @Deprecated + List<NodeTemplate> getPolicyTargetsFromOrigin(NodeTemplate nodeTemplate, String policyName); + + /** + * Get the node template of the topology template specified by name + * @param nodeTemplateName the name of the node template + * @return the node template + */ + @Deprecated + NodeTemplate getNodeTemplateByName(String nodeTemplateName); + + /** + * Get all the policies, which contain the specified node template as a target + * @param targetNode the node template + * @return the list of the policies + */ + @Deprecated + List<Policy> getPoliciesOfTarget(NodeTemplate targetNode); + + /** + * Get all the policies of the specified type, which contain the specified node template as a target + * @param nodeTemplate the node template + * @param policyTypeName the name of the policy type + * @return the list of the policies + */ + @Deprecated + List<Policy> getPoliciesOfTargetByToscaPolicyType(NodeTemplate nodeTemplate, String policyTypeName); + + /** + * Get all the groups of the origin component (nested topology template) of the node template + * @param nodeTemplate the node template + * @return the list of the groups + */ + @Deprecated + ArrayList<Group> getGroupsOfOriginOfNodeTemplate(NodeTemplate nodeTemplate); + + /** + * Get all groups of this of the main topology template (either VF or service) by specified tosca group type + * @param groupType the group type + * @return the list of the groups + */ + @Deprecated + ArrayList<Group> getGroupsOfTopologyTemplateByToscaGroupType(String groupType); + + /** + * Get all groups of this of the main topology template (either VF or service) + * @return the list of the groups + */ + @Deprecated + ArrayList<Group> getGroupsOfTopologyTemplate(); + + /** + * Get all groups of this of the origin component (nested topology template) of the node template by specified tosca group type + * @param nodeTemplate the node template + * @param groupType the group type + * @return the list of the groups + */ + @Deprecated + ArrayList<Group> getGroupsOfOriginOfNodeTemplateByToscaGroupType(NodeTemplate nodeTemplate, String groupType); + + /** + * Get members of the group belongs to the main topology template (either VF or service) by group name + * @param groupName the name of the group + * @return the list of the node templates + */ + @Deprecated + List<NodeTemplate> getGroupMembersFromTopologyTemplate(String groupName); + + /** + * Get members of the group belongs to the origin component (nested topology template) of the node template by group name + * @param nodeTemplate the node template + * @param groupName the name of the group + * @return the list of the node templates + */ + @Deprecated + List<NodeTemplate> getGroupMembersOfOriginOfNodeTemplate(NodeTemplate nodeTemplate, String groupName); + + /** + * Get inputs of the topology template including existing annotations + * @return the list of the inputs + */ + List<Input> getInputsWithAnnotations(); + + /** + * Get all interface details for given node template.<br> + * @return Map that contains the list of all interfaces and their definitions. + * If none found, an empty map will be returned. + */ + Map<String, List<InterfacesDef>> getInterfacesOf(NodeTemplate nt); + + /** + * Get all interface names for given node template.<br> + * @return List that contains the name of all interfaces. + * If none found, an empty list will be returned. + */ + public List<String> getInterfaces(NodeTemplate nt); + + /** + * Get all details for given node template and interface name.<br> + * @return List that contains the definitions of given interface name. + * If none found, an empty list will be returned. + */ + List<InterfacesDef> getInterfaceDetails(NodeTemplate nt, String interfaceName); + + /** + * Get all operation names for given node template and interface name.<br> + * @return List that contains the name of all operations for a given node template and interface name. + * If none found, an empty list will be returned. + */ + List<String> getAllInterfaceOperations(NodeTemplate nt, String interfaceName); + + /** + * Get interface details for a given node template, interface name and operation name.<br> + * @return InterfaceDef representing the operation details. + * If none found, null will be returned. + */ + InterfacesDef getInterfaceOperationDetails(NodeTemplate nt, String interfaceName, String operationName); + + /** + * Get property value for a property of given node template.<br> + * @param propertyNamePath valid name of property for search.<br> + * To find value in the datatype with datatype entry schema, the property name should be defined with # delimiter + * @param nodeTemplatePath path to the model node template that property value will be searched.<br> + * Path is based on the collection of the node templates names delimited by #. + * @return List of property values. If none found, empty list will be returned. + */ + @Deprecated + List<String> getPropertyLeafValueByPropertyNamePathAndNodeTemplatePath(String propertyNamePath, String nodeTemplatePath); + + boolean isNodeTypeSupported(NodeTemplate nodeTemplate); + + /** + * Retrieves details of one or more entity templates according to provided query parameters from corresponding topology template + * @param entityQuery Object describing the searched entity parameters. Includes one of following parameters: entity type, + * SDC (node template) type, tosca type as well as optional customizationUUID and UUID + * @param topologyTemplateQuery parameters of the topology template containing the above entity. + * Includes SDC type of the container and optional customizationUUID + * @param isRecursive indicates if the search is recursive starting from the required topology template . + * @return list of @{@link IEntityDetails} objects containing information about the found entities. + * If either no entities found or the provided query is incorrect, an empty list is returned + */ + List<IEntityDetails> getEntity(EntityQuery entityQuery, TopologyTemplateQuery topologyTemplateQuery, boolean isRecursive); + + /** + * Get the data_types + * @return list of data_type value + */ + HashSet<DataType> getDataTypes(); +}
\ No newline at end of file diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/Version.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/Version.java new file mode 100644 index 0000000..439c7bd --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/api/Version.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.api; + +public class Version implements Comparable<Version> { + + private String version; + + public final String get() { + return this.version; + } + + public Version(String version) { + if(version == null) + throw new IllegalArgumentException("Version can not be null"); + if(!version.matches("[0-9]+(\\.[0-9]+)*")) + throw new IllegalArgumentException("Invalid version format"); + this.version = version; + } + + @Override public int compareTo(Version that) { + if(that == null) + return 1; + String[] thisParts = this.get().split("\\."); + String[] thatParts = that.get().split("\\."); + int length = Math.max(thisParts.length, thatParts.length); + for(int i = 0; i < length; i++) { + int thisPart = i < thisParts.length ? + Integer.parseInt(thisParts[i]) : 0; + int thatPart = i < thatParts.length ? + Integer.parseInt(thatParts[i]) : 0; + if(thisPart < thatPart) + return -1; + if(thisPart > thatPart) + return 1; + } + return 0; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + + @Override public boolean equals(Object that) { + if(this == that) + return true; + if(that == null) + return false; + if(this.getClass() != that.getClass()) + return false; + return this.compareTo((Version) that) == 0; + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/Configuration.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/Configuration.java new file mode 100644 index 0000000..6c49f29 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/Configuration.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.config; + +import org.onap.sdc.tosca.parser.api.ConformanceLevel; + +public class Configuration { + + private ConformanceLevel conformanceLevel; + + public ConformanceLevel getConformanceLevel() { + return conformanceLevel; + } + + public void setConformanceLevel(ConformanceLevel conformanceLevel) { + this.conformanceLevel = conformanceLevel; + } +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/ConfigurationManager.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/ConfigurationManager.java new file mode 100644 index 0000000..6ad728e --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/ConfigurationManager.java @@ -0,0 +1,144 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.config; + +import com.google.common.base.Charsets; +import com.google.common.io.Resources; +import org.onap.sdc.tosca.parser.utils.YamlToObjectConverter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + + +public class ConfigurationManager { + + private static Logger log = LoggerFactory.getLogger(ConfigurationManager.class.getName()); + + private static final String CONFIGURATION_DIR = "config/"; + private static volatile ConfigurationManager instance; + + + Map<String, Object> configurations = new HashMap<String, Object>(); + + private ConfigurationManager() { + initialConfigObjectsFromFiles(); + } + + private void initialConfigObjectsFromFiles() { + loadConfigurationClass(ErrorConfiguration.class); + loadConfigurationClass(Configuration.class); + loadConfigurationClass(JtoscaValidationIssueConfiguration.class); + } + + private <T> void loadConfigurationClass(Class<T> clazz) { + T object = getObjectFromYaml(clazz); + configurations.put(clazz.getSimpleName(), object); + } + + private <T> void loadConfigurationClass(Class<T> clazz, String fileName) { + T object = getObjectFromYaml(clazz,fileName); + configurations.put(clazz.getSimpleName(), object); + } + + public static <T> T getObjectFromYaml(Class<T> className) { + return getObjectFromYaml(className, null); + } + + public static <T> T getObjectFromYaml(Class<T> className, String fileName) { + + + String configFileName = fileName != null ? fileName : calculateFileName(className); ; + + URL url = Resources.getResource(CONFIGURATION_DIR + configFileName); + String configFileContents = null; + try { + configFileContents = Resources.toString(url, Charsets.UTF_8); + } catch (IOException e) { + log.error("ConfigurationManager - Failed to load configuration file {}", configFileName, e); + } + YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter(); + T object = yamlToObjectConverter.convertFromString(configFileContents, className); + + return object; + } + + + public static ConfigurationManager getInstance() { + if (instance == null) { + synchronized (ConfigurationManager.class) { + if (instance == null) { + instance = new ConfigurationManager(); + } + } + } + return instance; + } + + private static <T> String calculateFileName(Class<T> className) { + + String[] words = className.getSimpleName().split("(?=\\p{Upper})"); + + StringBuilder builder = new StringBuilder(); + + // There cannot be a null value returned from "split" - words != null is + // redundant + // if (words != null) { + boolean isFirst = true; + for (int i = 0; i < words.length; i++) { + + String word = words[i]; + if (word != null && !word.isEmpty()) { + if (!isFirst) { + builder.append("-"); + } else { + isFirst = false; + } + builder.append(words[i].toLowerCase()); + } + } + return builder.toString() + ".yaml"; + + /* + * } else { return className.getSimpleName().toLowerCase() + Constants.YAML_SUFFIX; } + */ + + } + + public ErrorConfiguration getErrorConfiguration() { + return (ErrorConfiguration) configurations.get((ErrorConfiguration.class.getSimpleName())); + } + public JtoscaValidationIssueConfiguration getJtoscaValidationIssueConfiguration() { + return (JtoscaValidationIssueConfiguration) configurations.get((JtoscaValidationIssueConfiguration.class.getSimpleName())); + } + public void setJtoscaValidationIssueConfiguration(String fileName) { + loadConfigurationClass(JtoscaValidationIssueConfiguration.class, fileName); + } + public Configuration getConfiguration() { + return (Configuration) configurations.get((Configuration.class.getSimpleName())); + } + public void setErrorConfiguration(String fileName) { + loadConfigurationClass(ErrorConfiguration.class, fileName); + } +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/ErrorConfiguration.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/ErrorConfiguration.java new file mode 100644 index 0000000..1b1f2e2 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/ErrorConfiguration.java @@ -0,0 +1,46 @@ +/*- + * ============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.onap.sdc.tosca.parser.config; + +import java.util.Map; + +public class ErrorConfiguration { + + private Map<String, ErrorInfo> errors; + + public Map<String, ErrorInfo> getErrors() { + return errors; + } + + public void setErrors(Map<String, ErrorInfo> errors) { + this.errors = errors; + } + + public ErrorInfo getErrorInfo(String key) { + ErrorInfo clone = null; + ErrorInfo other = errors.get(key); + if (other != null) { + clone = new ErrorInfo(); + clone.cloneData(other); + } + return clone; + } +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/ErrorInfo.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/ErrorInfo.java new file mode 100644 index 0000000..52a92c4 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/ErrorInfo.java @@ -0,0 +1,59 @@ +/*- + * ============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.onap.sdc.tosca.parser.config; + +public class ErrorInfo { + + private String code; + private String message; + private boolean failOnError; + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public boolean getFailOnError() { + return failOnError; + } + + public void setFailOnError(boolean failOnError) { + this.failOnError = failOnError; + } + + public void cloneData(ErrorInfo other) { + this.code = other.getCode(); + this.message = other.getMessage(); + this.failOnError = other.getFailOnError(); + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/JToscaValidationIssueInfo.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/JToscaValidationIssueInfo.java new file mode 100644 index 0000000..2f9bb09 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/JToscaValidationIssueInfo.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.config; + +public class JToscaValidationIssueInfo { + + private String issueType; + private String sinceCsarConformanceLevel; + + public JToscaValidationIssueInfo() {} + + public String getIssueType() { + return issueType; + } + + public void setIssueType(String issueType) { + this.issueType = issueType; + } + + public String getSinceCsarConformanceLevel() { + return sinceCsarConformanceLevel; + } + + public void setSinceCsarConformanceLevel(String sinceCsarConformanceLevel) { + this.sinceCsarConformanceLevel = sinceCsarConformanceLevel; + } + + public void cloneData(JToscaValidationIssueInfo other) { + this.issueType = other.getIssueType(); + this.sinceCsarConformanceLevel = other.getSinceCsarConformanceLevel(); + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/JtoscaValidationIssueConfiguration.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/JtoscaValidationIssueConfiguration.java new file mode 100644 index 0000000..55912e6 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/JtoscaValidationIssueConfiguration.java @@ -0,0 +1,52 @@ +/*- + * ============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.onap.sdc.tosca.parser.config; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class JtoscaValidationIssueConfiguration { + + private Map<String, List<JToscaValidationIssueInfo>> validationIssues; + + public Map<String, List<JToscaValidationIssueInfo>> getValidationIssues() { + return validationIssues; + } + + public void setValidationIssues(Map<String, List<JToscaValidationIssueInfo>> validationIssues) { + this.validationIssues = validationIssues; + } + + public List<JToscaValidationIssueInfo> getJtoscaValidationIssueInfo(String key) { + List<JToscaValidationIssueInfo> clone = new ArrayList<>(); + List<JToscaValidationIssueInfo> other = validationIssues.get(key); + if (other != null) { + for (JToscaValidationIssueInfo item: other) { + JToscaValidationIssueInfo cloneitem = new JToscaValidationIssueInfo(); + cloneitem.cloneData(item); + clone.add(cloneitem); + } + } + return clone; + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/SdcToscaParserErrors.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/SdcToscaParserErrors.java new file mode 100644 index 0000000..c6375a5 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/config/SdcToscaParserErrors.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.config; + +import java.util.EnumMap; +import java.util.Map; + +import org.onap.sdc.toscaparser.api.utils.JToscaErrorCodes; + +public enum SdcToscaParserErrors { + + BAD_FORMAT, CONFORMANCE_LEVEL_ERROR, FILE_NOT_FOUND, GENERAL_ERROR; + + private static final Map<JToscaErrorCodes, SdcToscaParserErrors> JTOSCA_ERRORS = + new EnumMap<JToscaErrorCodes, SdcToscaParserErrors>(JToscaErrorCodes.class) {{ + + put(JToscaErrorCodes.GENERAL_ERROR, GENERAL_ERROR); + + put(JToscaErrorCodes.PATH_NOT_VALID, FILE_NOT_FOUND); + //CSAR contents problems + put(JToscaErrorCodes.MISSING_META_FILE, BAD_FORMAT); + put(JToscaErrorCodes.INVALID_META_YAML_CONTENT, BAD_FORMAT); + put(JToscaErrorCodes.ENTRY_DEFINITION_NOT_DEFINED, BAD_FORMAT); + put(JToscaErrorCodes.MISSING_ENTRY_DEFINITION_FILE, BAD_FORMAT); + put(JToscaErrorCodes.CSAR_TOSCA_VALIDATION_ERROR, BAD_FORMAT); + put(JToscaErrorCodes.INVALID_CSAR_FORMAT, BAD_FORMAT); + }}; + + public static SdcToscaParserErrors getSdcErrorByJToscaError(JToscaErrorCodes jToscaErrorCode) { + return JTOSCA_ERRORS.get(jToscaErrorCode); + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/EntityDetails.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/EntityDetails.java new file mode 100644 index 0000000..6054ac9 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/EntityDetails.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements; + +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.toscaparser.api.CapabilityAssignment; +import org.onap.sdc.toscaparser.api.EntityTemplate; +import org.onap.sdc.toscaparser.api.Property; +import org.onap.sdc.toscaparser.api.RequirementAssignment; +import org.onap.sdc.toscaparser.api.parameters.Input; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public abstract class EntityDetails implements IEntityDetails { + + private final EntityTemplate entityTemplate; + private final IEntityDetails parentNodeTemplate; + + EntityDetails(EntityTemplate entityTemplate) { + this.entityTemplate = entityTemplate; + this.parentNodeTemplate = EntityDetailsFactory.createEntityDetails(EntityTemplateType.NODE_TEMPLATE, entityTemplate.getParentNodeTemplate()); + } + + @Override + public String getName() { + return entityTemplate.getName(); + } + + public EntityTemplate getEntityTemplate() { + return entityTemplate; + } + + @Override + public Map<String, Property> getProperties() { + return entityTemplate.getProperties(); + } + + @Override + public List<IEntityDetails> getMemberNodes() { + return Collections.emptyList(); + } + + @Override + public IEntityDetails getParent() { + return parentNodeTemplate; + } + + @Override + public List<RequirementAssignment> getRequirements() { + return entityTemplate.getRequirements() + .getAll(); + } + + @Override + public List<CapabilityAssignment> getCapabilities() { + return entityTemplate.getCapabilities() + .getAll(); + } + + @Override + public List<String> getTargets() { + return Collections.emptyList(); + } + + @Override + public List<IEntityDetails> getTargetEntities() { + return Collections.emptyList(); + } + + @Override + public String getPath() { + StringBuilder pathBld = new StringBuilder(""); + EntityTemplate currentEntityParent = entityTemplate.getParentNodeTemplate(); + + while (currentEntityParent != null) { + if (pathBld.length() != 0) { + pathBld.insert(0,"#"); + } + pathBld.insert(0, currentEntityParent.getName()); + currentEntityParent = currentEntityParent.getParentNodeTemplate(); + } + return pathBld.toString(); + } + + @Override + public String getToscaType() { + return entityTemplate.getType(); + } + + @Override + public List<String> getMembers() + { return Collections.emptyList(); } + + @Override + public List<Input> getInputs(){ + return Collections.emptyList(); + } + + + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/EntityDetailsFactory.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/EntityDetailsFactory.java new file mode 100644 index 0000000..d56891e --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/EntityDetailsFactory.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements; + +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.toscaparser.api.EntityTemplate; + +public class EntityDetailsFactory { + + private EntityDetailsFactory(){} + + public static EntityDetails createEntityDetails(EntityTemplateType entityTemplateType, EntityTemplate entityTemplate) { + EntityDetails entityDetails = null; + if (entityTemplate != null && entityTemplateType != null) { + switch (entityTemplateType) { + case NODE_TEMPLATE: + entityDetails = new NodeTemplateEntityDetails(entityTemplate); + break; + case POLICY: + entityDetails = new PolicyEntityDetails(entityTemplate); + break; + case GROUP: + entityDetails = new GroupEntityDetails(entityTemplate); + break; + default: + break; + } + } + return entityDetails; + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/GroupEntityDetails.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/GroupEntityDetails.java new file mode 100644 index 0000000..664fe42 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/GroupEntityDetails.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements; + +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.toscaparser.api.EntityTemplate; +import org.onap.sdc.toscaparser.api.Group; +import org.onap.sdc.toscaparser.api.elements.Metadata; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class GroupEntityDetails extends EntityDetails { + private final Group group; + private final List<IEntityDetails> memberNodes; + + GroupEntityDetails(EntityTemplate entityTemplate) { + super(entityTemplate); + group = (Group)getEntityTemplate(); + if (group.getMemberNodes() != null) { + memberNodes = group.getMemberNodes() + .stream() + .map(m->EntityDetailsFactory.createEntityDetails(EntityTemplateType.NODE_TEMPLATE, m)) + .collect(Collectors.toList()); + } + else { + memberNodes = Collections.emptyList(); + } + } + + @Override + public EntityTemplateType getEntityType() { + return EntityTemplateType.GROUP; + } + + @Override + public List<IEntityDetails> getMemberNodes() { + return memberNodes; + } + + @Override + public Metadata getMetadata() { + return group.getMetadata(); + } + + @Override + public List<String> getMembers() { + if (group.getMembers() != null) { + return group.getMembers(); + } + return super.getMembers(); + } +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/NodeTemplateEntityDetails.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/NodeTemplateEntityDetails.java new file mode 100644 index 0000000..3b7aa99 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/NodeTemplateEntityDetails.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements; + +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.toscaparser.api.EntityTemplate; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.sdc.toscaparser.api.parameters.Input; + +import java.util.List; + +public class NodeTemplateEntityDetails extends EntityDetails { + + private final NodeTemplate nodeTemplate; + + NodeTemplateEntityDetails(EntityTemplate entityTemplate) { + super(entityTemplate); + nodeTemplate = (NodeTemplate)getEntityTemplate(); + } + + @Override + public EntityTemplateType getEntityType() { + return EntityTemplateType.NODE_TEMPLATE; + } + + @Override + public Metadata getMetadata() { + return nodeTemplate.getMetaData(); + } + + @Override + public List<Input> getInputs(){ + if (nodeTemplate.getSubMappingToscaTemplate()!= null) { + return nodeTemplate.getSubMappingToscaTemplate().getInputs(); + } + return super.getInputs(); + } +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/PolicyEntityDetails.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/PolicyEntityDetails.java new file mode 100644 index 0000000..91577b9 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/PolicyEntityDetails.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements; + +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.toscaparser.api.EntityTemplate; +import org.onap.sdc.toscaparser.api.Policy; +import org.onap.sdc.toscaparser.api.elements.Metadata; + +import java.util.List; +import java.util.stream.Collectors; + +public class PolicyEntityDetails extends EntityDetails { + + private static final String NODE_TEMPLATES_TARGET_TYPE = "node_templates"; + + private final Policy policy; + + PolicyEntityDetails(EntityTemplate entityTemplate) { + super(entityTemplate); + policy = (Policy)getEntityTemplate(); + } + + @Override + public EntityTemplateType getEntityType() { + return EntityTemplateType.POLICY; + } + + @Override + public Metadata getMetadata() { + return policy.getMetaDataObj(); + } + + @Override + public List<String> getTargets() { + if (policy.getTargets() != null) { + return policy.getTargets(); + } + return super.getTargets(); + } + + @Override + public List<IEntityDetails> getTargetEntities() { + if (policy.getTargetsType().equals(NODE_TEMPLATES_TARGET_TYPE)) { + return policy.getTargetsList() + .stream() + .map(o->EntityDetailsFactory.createEntityDetails(EntityTemplateType.NODE_TEMPLATE, (EntityTemplate)o)) + .collect(Collectors.toList()); + } + return policy.getTargetsList() + .stream() + .map(o->EntityDetailsFactory.createEntityDetails(EntityTemplateType.GROUP, (EntityTemplate)o)) + .collect(Collectors.toList()); + } +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/AllEntitiesQuery.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/AllEntitiesQuery.java new file mode 100644 index 0000000..d0585fa --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/AllEntitiesQuery.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements.queries; + +import com.google.common.collect.Lists; +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.ToscaTemplate; + +import java.util.List; + +/** + * Implements EntityQuery object for NodeTemplates, Groups and Policies + */ + +public class AllEntitiesQuery extends EntityQuery { + + AllEntitiesQuery() { + super(EntityTemplateType.ALL, null, null); + } + + @Override + public List<IEntityDetails> getEntitiesFromTopologyTemplate(NodeTemplate nodeTemplate) { + List<IEntityDetails> allEntities = Lists.newArrayList(); + if (nodeTemplate.getSubMappingToscaTemplate() != null) { + allEntities.addAll(GroupEntityQuery.convertGroupLisToEntityDetailsList(nodeTemplate.getSubMappingToscaTemplate().getGroups().stream())); + allEntities.addAll(NodeTemplateEntityQuery.convertNodeTemplatesListToEntityDetailsList(nodeTemplate.getSubMappingToscaTemplate().getNodeTemplates().stream())); + } + if (nodeTemplate.getOriginComponentTemplate() != null) { + allEntities.addAll(PolicyEntityQuery.convertPolicyLisToEntityDetailsList(nodeTemplate.getOriginComponentTemplate().getPolicies().stream())); + } + return allEntities; + } + + + @Override + public List<IEntityDetails> getEntitiesFromService(ToscaTemplate toscaTemplate) { + List<IEntityDetails> allEntities = Lists.newArrayList(); + allEntities.addAll(GroupEntityQuery.convertGroupLisToEntityDetailsList(toscaTemplate.getGroups().stream())); + allEntities.addAll(NodeTemplateEntityQuery.convertNodeTemplatesListToEntityDetailsList(toscaTemplate.getNodeTemplates().stream())); + allEntities.addAll(PolicyEntityQuery.convertPolicyLisToEntityDetailsList(toscaTemplate.getPolicies().stream())); + return allEntities; + } + +} + + diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/EntityQuery.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/EntityQuery.java new file mode 100644 index 0000000..e3af94f --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/EntityQuery.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements.queries; + +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.tosca.parser.enums.SdcTypes; +import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.ToscaTemplate; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Objects; + +/** + * This class describes an entity searched and retrieved by SDC Tosca Parser API + * It is used as the API input parameter. See the {@link org.onap.sdc.tosca.parser.api.ISdcCsarHelper} + */ +public abstract class EntityQuery { + + private static final Logger logger = LoggerFactory.getLogger(EntityQuery.class.getName()); + + private final EntityTemplateType entityType; + + private final SdcTypes nodeTemplateType; + + private final String toscaType; + + private String uUID; + + private String customizationUUID; + + EntityQuery(EntityTemplateType entityType, SdcTypes nodeTemplateType, String toscaType) { + this.entityType = entityType; + this.nodeTemplateType = nodeTemplateType; + this.toscaType = toscaType; + } + + void setUUID(String uUID) { + this.uUID = uUID; + } + + void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + + public abstract List<IEntityDetails> getEntitiesFromTopologyTemplate(NodeTemplate nodeTemplate); + + public abstract List<IEntityDetails> getEntitiesFromService(ToscaTemplate toscaTemplate); + + public EntityTemplateType getEntityType() { + return entityType; + } + + public SdcTypes getNodeTemplateType() { + return nodeTemplateType; + } + + public String getToscaType() { + return toscaType; + } + + public String getUUID() { + return uUID; + } + + public String getCustomizationUUID() { + return customizationUUID; + } + + boolean isSearchCriteriaMatched(Metadata metadata, String toscaType, String uuidKeyName, String cuuidKeyName) { + return Objects.nonNull(metadata) + && isStringMatchingOrNull(metadata.getValue(uuidKeyName), getUUID()) + && isStringMatchingOrNull(metadata.getValue(cuuidKeyName), getCustomizationUUID()) + && isStringMatchingOrNull(toscaType, getToscaType()); + } + + boolean isSearchCriteriaMatched(Metadata metadata, String toscaType) { + return isSearchCriteriaMatched(metadata, toscaType, SdcPropertyNames.PROPERTY_NAME_UUID, SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID); + } + + static boolean isStringMatchingOrNull(String currentUid, String uidInQuery) { + return uidInQuery == null || uidInQuery.equals(currentUid); + } + + public static EntityQueryBuilder newBuilder(EntityTemplateType entityTemplateType) { + return new EntityQueryBuilder(entityTemplateType); + } + + public static EntityQueryBuilder newBuilder(SdcTypes sdcType) { + return new EntityQueryBuilder(sdcType); + } + + @Override + public String toString() { + return String.format("EntityType=%s, nodeTemplateType=%s, toscaType=%s, uUID=%s, customizationUUID=%s", + entityType, nodeTemplateType, toscaType, uUID, customizationUUID); + } + + public static EntityQueryBuilder newBuilder(String toscaType) { + return new EntityQueryBuilder(toscaType); + } + + /** + * Builds instance of EntityQuery object according to provided parameters + */ + public static class EntityQueryBuilder { + private static final String GROUPS_NAME_SPACE = ".groups."; + private static final String POLICIES_NAME_SPACE = ".policies."; + + private EntityQuery entityQuery; + + private EntityQueryBuilder(EntityTemplateType entityTemplateType) { + switch(entityTemplateType) { + case NODE_TEMPLATE: + entityQuery = new NodeTemplateEntityQuery(); + break; + case GROUP: + entityQuery = new GroupEntityQuery(); + break; + case POLICY: + entityQuery = new PolicyEntityQuery(); + break; + case ALL: + entityQuery = new AllEntitiesQuery(); + break; + default: + String wrongTypeMsg = (String.format("Wrong entity query type: %s", entityTemplateType)); + logger.error(wrongTypeMsg); + throw new IllegalArgumentException(wrongTypeMsg); + } + } + + private EntityQueryBuilder(SdcTypes sdcType) { + entityQuery = new NodeTemplateEntityQuery(sdcType); + } + + private EntityQueryBuilder(String toscaType) { + if (toscaType.contains(GROUPS_NAME_SPACE)) { + entityQuery = new GroupEntityQuery(toscaType); + } + else if (toscaType.contains(POLICIES_NAME_SPACE)) { + entityQuery = new PolicyEntityQuery(toscaType); + } + else { + entityQuery = new NodeTemplateEntityQuery(toscaType); + } + } + + public EntityQueryBuilder uUID(String uUID) { + entityQuery.setUUID(uUID); + return this; + } + + public EntityQueryBuilder customizationUUID(String customizationUUID) { + entityQuery.setCustomizationUUID(customizationUUID); + return this; + } + + public EntityQuery build() { + return entityQuery; + } + } + + + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/GroupEntityQuery.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/GroupEntityQuery.java new file mode 100644 index 0000000..dba16d3 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/GroupEntityQuery.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements.queries; + +import com.google.common.collect.Lists; +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.elements.EntityDetailsFactory; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.toscaparser.api.Group; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.ToscaTemplate; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Implements EntityQuery object for Groups + */ +public class GroupEntityQuery extends EntityQuery { + + private static final String VF_MODULE_UUID = "vfModuleModelUUID"; + private static final String VF_MODULE_CUSTOMIZATION_UUID = "vfModuleModelCustomizationUUID"; + + GroupEntityQuery() { + super(EntityTemplateType.GROUP, null, null); + } + + @Override + public List<IEntityDetails> getEntitiesFromTopologyTemplate(NodeTemplate nodeTemplate) { + if (nodeTemplate.getSubMappingToscaTemplate() != null) { + return convertGroupLisToEntityDetailsList(filter(nodeTemplate.getSubMappingToscaTemplate().getGroups())); + } + return Lists.newArrayList(); + } + + @Override + public List<IEntityDetails> getEntitiesFromService(ToscaTemplate toscaTemplate) { + return convertGroupLisToEntityDetailsList(filter(toscaTemplate.getGroups())); + } + + GroupEntityQuery(String toscaType) { + super(EntityTemplateType.GROUP, null, toscaType); + } + + static List<IEntityDetails> convertGroupLisToEntityDetailsList(Stream<Group> groups) { + return groups.map(gr->EntityDetailsFactory.createEntityDetails(EntityTemplateType.GROUP, gr)) + .collect(Collectors.toList()); + } + + private Stream<Group> filter(List<Group> groupList) { + return groupList.stream() + .filter(gr->isSearchCriteriaMatched(gr.getMetadata(), gr.getType()) || + isSearchCriteriaMatched(gr.getMetadata(), gr.getType(), VF_MODULE_UUID, VF_MODULE_CUSTOMIZATION_UUID)); + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/NodeTemplateEntityQuery.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/NodeTemplateEntityQuery.java new file mode 100644 index 0000000..30784e7 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/NodeTemplateEntityQuery.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements.queries; + +import com.google.common.collect.Lists; +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.elements.EntityDetailsFactory; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.tosca.parser.enums.SdcTypes; +import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.ToscaTemplate; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Implements EntityQuery object for NodeTemplates + */ +public class NodeTemplateEntityQuery extends EntityQuery { + NodeTemplateEntityQuery() { + super(EntityTemplateType.NODE_TEMPLATE, null, null); + } + + NodeTemplateEntityQuery(SdcTypes nodeTemplateType) { + super(EntityTemplateType.NODE_TEMPLATE, nodeTemplateType, null); + } + + NodeTemplateEntityQuery(String toscaType) { + super(EntityTemplateType.NODE_TEMPLATE, null, toscaType); + } + + @Override + public List<IEntityDetails> getEntitiesFromTopologyTemplate(NodeTemplate nodeTemplate) { + if (nodeTemplate.getSubMappingToscaTemplate() != null) { + return convertNodeTemplatesListToEntityDetailsList(filter(nodeTemplate.getSubMappingToscaTemplate() + .getNodeTemplates())); + } + return Lists.newArrayList(); + } + + @Override + public List<IEntityDetails> getEntitiesFromService(ToscaTemplate toscaTemplate) { + return convertNodeTemplatesListToEntityDetailsList(filter(toscaTemplate.getNodeTemplates())); + } + + static List<IEntityDetails> convertNodeTemplatesListToEntityDetailsList(Stream<NodeTemplate> nodeTemplates) { + return nodeTemplates + .map(nt->EntityDetailsFactory.createEntityDetails(EntityTemplateType.NODE_TEMPLATE, nt)) + .collect(Collectors.toList()); + } + + private Stream<NodeTemplate> filter(List<NodeTemplate> nodeTemplateList) { + return nodeTemplateList.stream() + .filter(nt->isSearchCriteriaMatched(nt.getMetaData(), nt.getType())) + .filter(nt->getNodeTemplateType() == null || + isStringMatchingOrNull(nt.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE), + getNodeTemplateType().getValue())); + } + + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/PolicyEntityQuery.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/PolicyEntityQuery.java new file mode 100644 index 0000000..f93505d --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/PolicyEntityQuery.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements.queries; + +import com.google.common.collect.Lists; +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.elements.EntityDetailsFactory; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.Policy; +import org.onap.sdc.toscaparser.api.ToscaTemplate; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Implements EntityQuery object for Policies + */ +public class PolicyEntityQuery extends EntityQuery { + + PolicyEntityQuery() { + super(EntityTemplateType.POLICY, null, null); + } + + PolicyEntityQuery(String toscaType) { + super(EntityTemplateType.POLICY, null, toscaType); + } + + @Override + public List<IEntityDetails> getEntitiesFromTopologyTemplate(NodeTemplate nodeTemplate) { + if (nodeTemplate.getOriginComponentTemplate() != null) { + return convertPolicyLisToEntityDetailsList(filter(nodeTemplate.getOriginComponentTemplate().getPolicies())); + } + return Lists.newArrayList(); + } + + @Override + public List<IEntityDetails> getEntitiesFromService(ToscaTemplate toscaTemplate) { + return convertPolicyLisToEntityDetailsList(filter(toscaTemplate.getPolicies())); + } + + static List<IEntityDetails> convertPolicyLisToEntityDetailsList(Stream<Policy> policies) { + return policies + .map(p->EntityDetailsFactory.createEntityDetails(EntityTemplateType.POLICY, p)) + .collect(Collectors.toList()); + } + + private Stream<Policy> filter(List<Policy> policyList) { + return policyList.stream() + .filter(p->isSearchCriteriaMatched(p.getMetaDataObj(), p.getType())); + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/TopologyTemplateQuery.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/TopologyTemplateQuery.java new file mode 100644 index 0000000..99dd7fd --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/elements/queries/TopologyTemplateQuery.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.elements.queries; + +import org.onap.sdc.tosca.parser.enums.SdcTypes; +import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Objects; + +/** + * This class describes a node template instance containing an entity searched and retrieved by SDC Tosca Parser API + * It is used as the API input parameter. See the {@link org.onap.sdc.tosca.parser.api.ISdcCsarHelper} + */ +public class TopologyTemplateQuery { + private static final Logger logger = LoggerFactory.getLogger(TopologyTemplateQuery.class.getName()); + + void setCustomizationUUID(String customizationUUID) { + this.customizationUUID = customizationUUID; + } + + private final SdcTypes sdcType; + + private String customizationUUID; + + private TopologyTemplateQuery(SdcTypes sdcType) { + this.sdcType = sdcType; + } + + public static TopologyTemplateQueryBuilder newBuilder(SdcTypes sdcType) { + if (!SdcTypes.isComplex(sdcType.getValue())) { + String wrongTypeMsg = (String.format("Given type is not Topology template %s", sdcType)); + logger.error(wrongTypeMsg); + throw new IllegalArgumentException(wrongTypeMsg); + } + return new TopologyTemplateQueryBuilder(sdcType); + } + + public SdcTypes getNodeTemplateType() { + return sdcType; + } + + public String getCustomizationUUID() { + return customizationUUID; + } + + public Boolean isMatchingSearchCriteria(NodeTemplate nodeTemplate) { + boolean isMatched = Objects.nonNull(nodeTemplate.getMetaData()) && isSearchedTemplate(nodeTemplate.getMetaData()); + if(logger.isDebugEnabled()) { + logger.debug("Node template {} is{} matching search criteria", nodeTemplate.getName(), isMatched ? "" : " not"); + } + return isMatched; + } + + public boolean isSameSdcType(Metadata metadata) { + final String nodeType = metadata.getValue(SdcPropertyNames.PROPERTY_NAME_TYPE); + return Objects.nonNull(nodeType) && ( + sdcType.getValue().equals(nodeType) || isServiceSearched(nodeType)); + } + + private boolean isSearchedTemplate(Metadata metadata) { + return isSameSdcType(metadata) && + (sdcType == SdcTypes.SERVICE || + //don't check customizationUUID for service + EntityQuery.isStringMatchingOrNull(metadata.getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID), + getCustomizationUUID())); + } + + private boolean isServiceSearched(String nodeType) { + return sdcType == SdcTypes.SERVICE && SdcTypes.isComplex(nodeType); + } + + @Override + public String toString() { + return String.format("sdcType=%s, customizationUUID=%s", sdcType.getValue(), customizationUUID); + } + + public static class TopologyTemplateQueryBuilder { + private TopologyTemplateQuery topologyTemplateQuery; + private TopologyTemplateQueryBuilder(SdcTypes sdcType) { topologyTemplateQuery = new TopologyTemplateQuery(sdcType);} + + public TopologyTemplateQueryBuilder customizationUUID(String customizationUUID) { + topologyTemplateQuery.setCustomizationUUID(customizationUUID); + return this; + } + + public TopologyTemplateQuery build() { + return topologyTemplateQuery; + } + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/EntityTemplateType.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/EntityTemplateType.java new file mode 100644 index 0000000..b35a997 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/EntityTemplateType.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.enums; + +/** + * Describes types of entities for search + */ +public enum EntityTemplateType { + NODE_TEMPLATE, + GROUP, + POLICY, + ALL; + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/FilterType.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/FilterType.java new file mode 100644 index 0000000..028242f --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/FilterType.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.enums; + +public enum FilterType { + + CONTAINS("contains"){ + @Override + public boolean isMatch(String value, String pattern) { + return value.contains(pattern); + } + }, + EQUALS("equals"){ + @Override + public boolean isMatch(String value, String pattern) { + return value.equals(pattern); + } + }; + + String filterName; + + FilterType(String name) { + this.filterName = name; + } + + public abstract boolean isMatch(String value, String pattern); + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/JToscaValidationIssueType.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/JToscaValidationIssueType.java new file mode 100644 index 0000000..0247ef8 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/JToscaValidationIssueType.java @@ -0,0 +1,26 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.enums; + +public enum JToscaValidationIssueType { + CRITICAL, + WARNING +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/PropertySchemaType.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/PropertySchemaType.java new file mode 100644 index 0000000..656f3ce --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/PropertySchemaType.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.enums; + + +import java.util.Arrays; +import java.util.NoSuchElementException; + +import static org.onap.sdc.tosca.parser.enums.PropertySchemaType.PropertySchemaComplexity.Complex; +import static org.onap.sdc.tosca.parser.enums.PropertySchemaType.PropertySchemaComplexity.DataType; +import static org.onap.sdc.tosca.parser.enums.PropertySchemaType.PropertySchemaComplexity.Simple; + +public enum PropertySchemaType { + + STRING(Simple, "string"), + INTEGER(Simple, "integer"), + BOOLEAN(Simple, "boolean"), + FLOAT(Simple, "float"), + NUMBER(Simple, "number"), + TIMESTAMP(Simple, "timestamp"), + RANGE(Simple, "range"), + VERSION(Simple, "version"), + SCALAR_UNIT_SIZE(Simple, "scalar-unit.size"), + SCALAR_UNIT_TIME(Simple, "scalar-unit.time"), + SCALAR_UNIT_FREQUENCY(Simple, "scalar-unit.frequency"), + LIST(Complex, "list"), + MAP(Complex, "map"), + DATATYPE(DataType, "datatypes"); + + private PropertySchemaComplexity complexity; + private String schemaType; + + PropertySchemaType(PropertySchemaComplexity complexity, String schemaType) { + this.complexity = complexity; + this.schemaType = schemaType; + } + + public PropertySchemaComplexity getSchemaTypeComplexity() { + return complexity; + } + + public String getSchemaTypeName() { + return schemaType; + } + + public enum PropertySchemaComplexity { + Simple, Complex, DataType + } + + public static PropertySchemaType getEnumByValue(String type){ + if (type == null) { + throwNoSuchElementException(null); + } + + if (type.contains(DATATYPE.getSchemaTypeName())) { + return DATATYPE; + } + PropertySchemaType propertySchemaType = Arrays.stream(PropertySchemaType.values()) + .filter(v->v.getSchemaTypeName().equals(type)) + .findFirst().orElse(null); + if (propertySchemaType == null) { + throwNoSuchElementException(type); + } + return propertySchemaType; + } + + private static void throwNoSuchElementException(String type) { + throw new NoSuchElementException(String.format("Value %s is not defined in %s", type, PropertySchemaType.class.getName())); + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/SdcTypes.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/SdcTypes.java new file mode 100644 index 0000000..e1339f9 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/enums/SdcTypes.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.enums; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public enum SdcTypes { + + CP("CP"), VL("VL"), VF("VF"), CR("CR"), VFC("VFC"), PNF("PNF"), SERVICE("Service"), CVFC("CVFC"), + SERVICE_PROXY("Service Proxy"), CONFIGURATION("Configuration"), VFC_ALLOTTED_RESOURCE("AllottedResource") ; + + private String value; + + private static List<String> complexTypes = Arrays.asList(VF, PNF, CR, SERVICE, CVFC).stream().map(SdcTypes::getValue).collect(Collectors.toList()); + + SdcTypes(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public static boolean isComplex(String sdcType) { + return complexTypes.contains(sdcType); + } +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/exceptions/SdcToscaParserException.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/exceptions/SdcToscaParserException.java new file mode 100644 index 0000000..e163295 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/exceptions/SdcToscaParserException.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.exceptions; + +public class SdcToscaParserException extends Exception { + + private static final long serialVersionUID = 626014844866501196L; + private String code; + + public SdcToscaParserException(String string, String code) { + super(string); + this.code = code; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/QueryProcessor.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/QueryProcessor.java new file mode 100644 index 0000000..6fd5ce5 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/QueryProcessor.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.impl; + +import com.google.common.collect.Lists; +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.elements.queries.EntityQuery; +import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; +import org.onap.sdc.tosca.parser.enums.SdcTypes; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.ToscaTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * Performs search for entity templates inside node template according to query criteria + */ +class QueryProcessor { + private static final Logger logger = LoggerFactory.getLogger(QueryProcessor.class.getName()); + + private final EntityQuery entityQuery; + private final TopologyTemplateQuery topologyTemplateQuery; + private final ToscaTemplate toscaTemplate; + private boolean isRecursive = false; + + QueryProcessor(ToscaTemplate toscaTemplate, EntityQuery entityQuery, TopologyTemplateQuery topologyTemplateQuery, boolean isRecursive) { + this.toscaTemplate = toscaTemplate; + this.entityQuery = entityQuery == null ? EntityQuery.newBuilder(EntityTemplateType.ALL).build() : entityQuery; + this.topologyTemplateQuery = topologyTemplateQuery; + this.isRecursive = isRecursive; + } + + List<IEntityDetails> doQuery() { + List<IEntityDetails> entityDetailsList = Lists.newArrayList(); + if (isServiceSearch()) { + //search for entities inside the service + if (logger.isDebugEnabled()) { + logger.debug("Service {} is searched for {}", toscaTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_NAME), entityQuery); + } + entityDetailsList.addAll(entityQuery.getEntitiesFromService(toscaTemplate)); + + if (!isRecursive) { + return entityDetailsList; + } + } + + List<NodeTemplate> foundTopologyTemplates = getInternalTopologyTemplates(toscaTemplate.getNodeTemplates(), false); + if (isRecursive) { + if (logger.isDebugEnabled()) { + logger.debug("Search for entities recursively"); + } + //go over internal topology templates of the found templates + // and search for instances of the same type + //if the queried topology template is "SERVICE", search for all instances of templates in the service + List<NodeTemplate> internalTopologyTemplates = foundTopologyTemplates.stream() + .filter(nt->nt.getSubMappingToscaTemplate() != null) + .map(nt->getInternalTopologyTemplates(nt.getSubMappingToscaTemplate().getNodeTemplates(), true)) + .flatMap(List::stream) + .collect(Collectors.toList()); + foundTopologyTemplates.addAll(internalTopologyTemplates); + } + if (logger.isDebugEnabled()) { + logger.debug("Found topology templates {} matching following query criteria: {}", + foundTopologyTemplates, topologyTemplateQuery); + } + //go over all node templates found according to query criteria and recursive flag and + // search for the requested entities. + entityDetailsList.addAll(searchEntitiesInsideTopologyTemplates(foundTopologyTemplates)); + + return entityDetailsList; + } + + private Map<String, NodeTemplate> convertListToMap(List<NodeTemplate> nodeTemplateList) { + // we use map to avoid duplicate search through same node templates + return nodeTemplateList.stream() + .collect(Collectors.toMap(NodeTemplate::getName, nt->nt, (nt1, nt2)->nt1)); + } + + private List<IEntityDetails> searchEntitiesInsideTopologyTemplates(List<NodeTemplate> foundTopologyTemplates) { + return convertListToMap(foundTopologyTemplates) + .values() + .stream() + .map(entityQuery::getEntitiesFromTopologyTemplate) + .flatMap(List::stream) + .collect(Collectors.toList()); + } + + private boolean isServiceSearch() { + return topologyTemplateQuery.getNodeTemplateType() == SdcTypes.SERVICE; + } + + private List<NodeTemplate> getInternalTopologyTemplates(List<NodeTemplate> nodeTemplateList, boolean isRecursive) { + return nodeTemplateList + .stream() + .map(child->getTopologyTemplatesByQuery(child, isRecursive)) + .flatMap(List::stream) + .collect(Collectors.toList()); + } + + private List<NodeTemplate> getTopologyTemplatesByQuery(NodeTemplate current, boolean isRecursive) { + List<NodeTemplate> topologyTemplateList = Lists.newArrayList(); + + boolean isTopologyTemplateFound = isRecursive ? + SdcTypes.isComplex(current.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)) + : topologyTemplateQuery.isMatchingSearchCriteria(current); + if (isTopologyTemplateFound) { + topologyTemplateList.add(current); + if (!isRecursive) { + //recursion stop condition + return topologyTemplateList; + } + } + if (SdcTypes.isComplex(current.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)) && + current.getSubMappingToscaTemplate() != null) { + //search the node template inside a given topology template + topologyTemplateList.addAll(current.getSubMappingToscaTemplate().getNodeTemplates() + .stream() + .map(nt->getTopologyTemplatesByQuery(nt, isRecursive)) + .flatMap(List::stream) + .collect(Collectors.toList())); + } + return topologyTemplateList; + } + + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/SdcCsarHelperImpl.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/SdcCsarHelperImpl.java new file mode 100644 index 0000000..95530f0 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/SdcCsarHelperImpl.java @@ -0,0 +1,1230 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.impl; + +import static java.util.stream.Collectors.toList; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.config.ConfigurationManager; +import org.onap.sdc.tosca.parser.elements.queries.EntityQuery; +import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery; +import org.onap.sdc.tosca.parser.enums.FilterType; +import org.onap.sdc.tosca.parser.enums.PropertySchemaType; +import org.onap.sdc.tosca.parser.enums.SdcTypes; +import org.onap.sdc.tosca.parser.utils.GeneralUtility; +import org.onap.sdc.tosca.parser.utils.PropertyUtils; +import org.onap.sdc.tosca.parser.utils.SdcToscaUtility; +import org.onap.sdc.toscaparser.api.CapabilityAssignment; +import org.onap.sdc.toscaparser.api.CapabilityAssignments; +import org.onap.sdc.toscaparser.api.Group; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.Policy; +import org.onap.sdc.toscaparser.api.Property; +import org.onap.sdc.toscaparser.api.RequirementAssignment; +import org.onap.sdc.toscaparser.api.RequirementAssignments; +import org.onap.sdc.toscaparser.api.SubstitutionMappings; +import org.onap.sdc.toscaparser.api.TopologyTemplate; +import org.onap.sdc.toscaparser.api.ToscaTemplate; +import org.onap.sdc.toscaparser.api.elements.DataType; +import org.onap.sdc.toscaparser.api.elements.InterfacesDef; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.sdc.toscaparser.api.elements.NodeType; +import org.onap.sdc.toscaparser.api.functions.Function; +import org.onap.sdc.toscaparser.api.parameters.Input; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdcCsarHelperImpl implements ISdcCsarHelper { + + private static final String PATH_DELIMITER = "#"; + private static final String CUSTOMIZATION_UUID = "customizationUUID"; + private ToscaTemplate toscaTemplate; + private ConfigurationManager configurationManager; + private static Logger log = LoggerFactory.getLogger(SdcCsarHelperImpl.class.getName()); + + public SdcCsarHelperImpl(ToscaTemplate toscaTemplate) { + this.toscaTemplate = toscaTemplate; + } + + public SdcCsarHelperImpl(ToscaTemplate toscaTemplate, ConfigurationManager configurationManager) { + this.toscaTemplate = toscaTemplate; + this.configurationManager = configurationManager; + } + + @Override + public List<Policy> getPoliciesOfTarget(NodeTemplate nodeTemplate) { + return getPoliciesOfNodeTemplate(nodeTemplate.getName()) + .stream() + .sorted(Policy::compareTo) + .collect(toList()); + } + + @Override + public List<Policy> getPoliciesOfOriginOfNodeTemplate(NodeTemplate nodeTemplate) { + if(StringUtils.isNotEmpty(nodeTemplate.getName())){ + return getNodeTemplateByName(nodeTemplate.getName()).getOriginComponentTemplate().getPolicies(); + } + return new ArrayList<>(); + } + + @Override + public List<Policy> getPoliciesOfTargetByToscaPolicyType(NodeTemplate nodeTemplate, String policyTypeName) { + return getPoliciesOfNodeTemplate(nodeTemplate.getName()) + .stream() + .filter(p->p.getType().equals(policyTypeName)) + .sorted(Policy::compareTo) + .collect(toList()); + } + + @Override + public List<Policy> getPoliciesOfOriginOfNodeTemplateByToscaPolicyType(NodeTemplate nodeTemplate, String policyTypeName) { + return getPoliciesOfOriginOfNodeTemplate(nodeTemplate) + .stream() + .filter(p->p.getType().equals(policyTypeName)) + .sorted(Policy::compareTo) + .collect(toList()); + } + + @Override + public List<NodeTemplate> getPolicyTargetsFromTopologyTemplate(String policyName) { + if(toscaTemplate.getNodeTemplates() == null){ + return new ArrayList<>(); + } + List<String> targetNames = getPolicyTargets(policyName); + return toscaTemplate.getNodeTemplates().stream() + .filter(nt->targetNames.contains(nt.getName())) + .collect(toList()); + } + + @Override + public List<NodeTemplate> getPolicyTargetsFromOrigin(NodeTemplate nodeTemplate, String policyName) { + if(StringUtils.isNotEmpty(nodeTemplate.getName())){ + Optional<Policy> policyOpt = getNodeTemplateByName(nodeTemplate.getName()) + .getOriginComponentTemplate() + .getPolicies() + .stream() + .filter(p -> p.getName() + .equals(policyName)) + .findFirst(); + if(policyOpt.isPresent()){ + List<String> targets = policyOpt.get().getTargets(); + if (targets != null) { + return nodeTemplate.getOriginComponentTemplate().getNodeTemplates() + .stream() + .filter(nt -> targets.contains(nt.getName())).collect(Collectors.toList()); + } + } + } + return new ArrayList<>(); + } + + @Override + public List<Policy> getPoliciesOfTopologyTemplate(){ + if(toscaTemplate.getPolicies() == null) + return new ArrayList<>(); + return toscaTemplate.getPolicies() + .stream() + .sorted(Policy::compareTo) + .collect(toList()); + } + + @Override + public List<Policy> getPoliciesOfTopologyTemplateByToscaPolicyType(String policyTypeName){ + if(toscaTemplate.getPolicies() == null) + return new ArrayList<>(); + return toscaTemplate.getPolicies() + .stream() + .filter(p->p.getType().equals(policyTypeName)) + .sorted(Policy::compareTo) + .collect(toList()); + } + + public NodeTemplate getNodeTemplateByName(String nodeTemplateName) { + if(toscaTemplate.getNodeTemplates() == null) + return null; + return toscaTemplate.getNodeTemplates() + .stream() + .filter(nt -> nt.getName().equals(nodeTemplateName)) + .findFirst().orElse(null); + } + + private List<Policy> getPoliciesOfNodeTemplate(String nodeTemplateName) { + if(toscaTemplate.getPolicies() == null) + return new ArrayList<>(); + return toscaTemplate.getPolicies() + .stream() + .filter(p -> p.getTargets()!= null && p.getTargets().contains(nodeTemplateName)) + .collect(toList()); + } + + private List<String> getPolicyTargets(String policyName) { + return getPolicyByName(policyName).map(Policy::getTargets).orElse(new ArrayList<>()); + } + + private List<String> getGroupMembers(String groupName) { + return getGroupByName(groupName).map(Group::getMembers).orElse(new ArrayList<>()); + } + + private Optional<Policy> getPolicyByName(String policyName) { + if(toscaTemplate.getPolicies() == null) + return Optional.empty(); + return toscaTemplate.getPolicies() + .stream() + .filter(p -> p.getName().equals(policyName)).findFirst(); + } + + private Optional<Group> getGroupByName(String groupName) { + if(toscaTemplate.getGroups() == null) + return Optional.empty(); + return toscaTemplate.getGroups() + .stream() + .filter(g -> g.getName().equals(groupName)).findFirst(); + } + + @Override + //Sunny flow - covered with UT, flat and nested + public String getNodeTemplatePropertyLeafValue(NodeTemplate nodeTemplate, String leafValuePath) { + Object value = getNodeTemplatePropertyValueAsObject(nodeTemplate, leafValuePath); + return value == null || value instanceof Function ? null : String.valueOf(value); + } + + @Override + public Object getNodeTemplatePropertyValueAsObject(NodeTemplate nodeTemplate, String leafValuePath) { + if (nodeTemplate == null) { + log.error("getNodeTemplatePropertyValueAsObject - nodeTemplate is null"); + return null; + } + if (GeneralUtility.isEmptyString(leafValuePath)) { + log.error("getNodeTemplatePropertyValueAsObject - leafValuePath is null or empty"); + return null; + } + String[] split = getSplittedPath(leafValuePath); + LinkedHashMap<String, Property> properties = nodeTemplate.getProperties(); + return PropertyUtils.processProperties(split, properties); + } + + public Map<String, Map<String, Object>> getCpPropertiesFromVfcAsObject(NodeTemplate vfc) { + if (vfc == null) { + log.error("getCpPropertiesFromVfc - vfc is null"); + return new HashMap<>(); + } + + String presetProperty = "_ip_requirements"; + Map<String, Map<String, Object>> cps = new HashMap<>(); + + Map<String, Property> props = vfc.getProperties(); + if (props != null) { + // find all port names by pre-set property (ip_requirements) + for (Map.Entry<String, Property> entry : props.entrySet()) { + if (entry.getKey().endsWith(presetProperty)) { + String portName = entry.getKey().replaceAll(presetProperty, ""); + cps.put(portName, new HashMap<>()); + } + } + + findPutAllPortsProperties(cps, props); + } + + return cps; + } + + private void findPutAllPortsProperties(Map<String, Map<String, Object>> cps, Map<String, Property> props) { + if (!cps.isEmpty()) { + for (Entry<String, Map<String, Object>> port : cps.entrySet()) { + for (Map.Entry<String, Property> property: props.entrySet()) { + if (property.getKey().startsWith(port.getKey())) { + String portProperty = property.getKey().replaceFirst(port.getKey() + "_", ""); + if (property.getValue() != null) { + cps.get(port.getKey()).put(portProperty, property.getValue().getValue()); + } + } + } + } + } + } + + public Map<String, Map<String, Object>> getCpPropertiesFromVfc(NodeTemplate vfc) { + + if (vfc == null) { + log.error("getCpPropertiesFromVfc - vfc is null"); + return new HashMap<>(); + } + + String presetProperty = "_ip_requirements"; + Map<String, Map<String, Object>> cps = new HashMap<>(); + + Map<String, Property> props = vfc.getProperties(); + if (props != null) { + // find all port names by pre-set property (ip_requirements) + for (Map.Entry<String, Property> entry : props.entrySet()) { + if (entry.getKey().endsWith(presetProperty)) { + String portName = entry.getKey().replaceAll(presetProperty, ""); + cps.put(portName, new HashMap<>()); + } + } + findBuildPutAllPortsProperties(cps, props); + } + + return cps; + } + + private void findBuildPutAllPortsProperties(Map<String, Map<String, Object>> cps, Map<String, Property> props) { + if (!cps.isEmpty()) { + for (Entry<String, Map<String, Object>> port : cps.entrySet()) { + for (Map.Entry<String, Property> property: props.entrySet()) { + if (property.getKey().startsWith(port.getKey())) { + Map<String, Object> portPaths = new HashMap<>(); + String portProperty = property.getKey().replaceFirst(port.getKey() + "_", ""); + buildPathMappedToValue(portProperty, property.getValue().getValue(), portPaths); + cps.get(port.getKey()).putAll(portPaths); + } + } + } + } + } + + @SuppressWarnings("unchecked") + private void buildPathMappedToValue(String path, Object property, Map<String, Object> pathsMap) { + if (property instanceof Map) { + for (Map.Entry<String, Object> item : ((Map<String, Object>) property).entrySet()) { + if (item.getValue() instanceof Map || item.getValue() instanceof List) { + buildPathMappedToValue(path + PATH_DELIMITER + item.getKey(), item.getValue(), pathsMap); + } else { + pathsMap.put(path + PATH_DELIMITER + item.getKey(), item.getValue()); + } + } + } else if (property instanceof List) { + for (Object item: (List<Object>)property) { + buildPathMappedToValue(path, item, pathsMap); + } + } else { + pathsMap.put(path, property); + } + + } + + @Override + //Sunny flow - covered with UT + public List<NodeTemplate> getServiceVlList() { + return getNodeTemplateBySdcType(toscaTemplate.getTopologyTemplate(), SdcTypes.VL); + } + + @Override + //Sunny flow - covered with UT + public List<NodeTemplate> getServiceVfList() { + return getNodeTemplateBySdcType(toscaTemplate.getTopologyTemplate(), SdcTypes.VF); + } + + @Override + //Sunny flow - covered with UT + public String getMetadataPropertyValue(Metadata metadata, String metadataPropertyName) { + if (GeneralUtility.isEmptyString(metadataPropertyName)) { + log.error("getMetadataPropertyValue - the metadataPropertyName is null or empty"); + return null; + } + if (metadata == null) { + log.error("getMetadataPropertyValue - the metadata is null"); + return null; + } + return metadata.getValue(metadataPropertyName); + } + + + @Override + //Sunny flow - covered with UT + public List<NodeTemplate> getServiceNodeTemplatesByType(String nodeType) { + if (GeneralUtility.isEmptyString(nodeType)) { + log.error("getServiceNodeTemplatesByType - nodeType - is null or empty"); + return new ArrayList<>(); + } + + List<NodeTemplate> res = new ArrayList<>(); + List<NodeTemplate> nodeTemplates = toscaTemplate.getNodeTemplates(); + for (NodeTemplate nodeTemplate : nodeTemplates) { + if (nodeType.equals(nodeTemplate.getTypeDefinition().getType())) { + res.add(nodeTemplate); + } + } + + return res; + } + + + @Override + public List<NodeTemplate> getServiceNodeTemplates() { + return toscaTemplate.getNodeTemplates(); + } + + @Override + //Sunny flow - covered with UT + public List<NodeTemplate> getVfcListByVf(String vfCustomizationId) { + if (GeneralUtility.isEmptyString(vfCustomizationId)) { + log.error("getVfcListByVf - vfCustomizationId - is null or empty"); + return new ArrayList<>(); + } + + List<NodeTemplate> serviceVfList = getServiceVfList(); + NodeTemplate vfInstance = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationId); + List<NodeTemplate> vfcs = getNodeTemplateBySdcType(vfInstance, SdcTypes.VFC); + vfcs.addAll(getNodeTemplateBySdcType(vfInstance, SdcTypes.CVFC)); + + return vfcs; + } + + @Override + //Sunny flow - covered with UT + public List<Group> getVfModulesByVf(String vfCustomizationUuid) { + List<NodeTemplate> serviceVfList = getServiceVfList(); + NodeTemplate nodeTemplateByCustomizationUuid = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationUuid); + if (nodeTemplateByCustomizationUuid != null) { + String name = nodeTemplateByCustomizationUuid.getName(); + String normaliseComponentInstanceName = SdcToscaUtility.normaliseComponentInstanceName(name); + List<Group> serviceLevelGroups = toscaTemplate.getTopologyTemplate().getGroups(); + log.debug("getVfModulesByVf - VF node template name {}, normalized name {}. Searching groups on service level starting with VF normalized name...", name, normaliseComponentInstanceName); + if (serviceLevelGroups != null) { + return serviceLevelGroups + .stream() + .filter(x -> "org.openecomp.groups.VfModule".equals(x.getTypeDefinition().getType()) && x.getName().startsWith(normaliseComponentInstanceName)) + .collect(toList()); + } + } + return new ArrayList<>(); + } + + @Override + //Sunny flow - covered with UT + public String getServiceInputLeafValueOfDefault(String inputLeafValuePath) { + if (GeneralUtility.isEmptyString(inputLeafValuePath)) { + log.error("getServiceInputLeafValueOfDefault - inputLeafValuePath is null or empty"); + return null; + } + + String[] split = getSplittedPath(inputLeafValuePath); + if (split.length < 2 || !split[1].equals("default")) { + log.error("getServiceInputLeafValue - inputLeafValuePath should be of format <input name>#default[optionally #<rest of path>] "); + return null; + } + + List<Input> inputs = toscaTemplate.getInputs(); + if (inputs != null) { + Optional<Input> findFirst = inputs.stream().filter(x -> x.getName().equals(split[0])).findFirst(); + if (findFirst.isPresent()) { + Input input = findFirst.get(); + Object current = input.getDefault(); + Object property = PropertyUtils.iterateProcessPath(2, current, split); + return property == null || property instanceof Function? null : String.valueOf(property); + } + } + log.error("getServiceInputLeafValue - value not found"); + return null; + } + + @Override + public Object getServiceInputLeafValueOfDefaultAsObject(String inputLeafValuePath) { + if (GeneralUtility.isEmptyString(inputLeafValuePath)) { + log.error("getServiceInputLeafValueOfDefaultAsObject - inputLeafValuePath is null or empty"); + return null; + } + + String[] split = getSplittedPath(inputLeafValuePath); + if (split.length < 2 || !split[1].equals("default")) { + log.error("getServiceInputLeafValueOfDefaultAsObject - inputLeafValuePath should be of format <input name>#default[optionally #<rest of path>] "); + return null; + } + + List<Input> inputs = toscaTemplate.getInputs(); + if (inputs != null) { + Optional<Input> findFirst = inputs.stream().filter(x -> x.getName().equals(split[0])).findFirst(); + if (findFirst.isPresent()) { + Input input = findFirst.get(); + Object current = input.getDefault(); + return PropertyUtils.iterateProcessPath(2, current, split); + } + } + log.error("getServiceInputLeafValueOfDefaultAsObject - value not found"); + return null; + } + + private String[] getSplittedPath(String leafValuePath) { + return leafValuePath.split(PATH_DELIMITER); + } + + + @Override + //Sunny flow - covered with UT + public String getServiceSubstitutionMappingsTypeName() { + SubstitutionMappings substitutionMappings = toscaTemplate.getTopologyTemplate().getSubstitutionMappings(); + if (substitutionMappings == null) { + log.debug("getServiceSubstitutionMappingsTypeName - No Substitution Mappings defined"); + return null; + } + + NodeType nodeType = substitutionMappings.getNodeDefinition(); + if (nodeType == null) { + log.debug("getServiceSubstitutionMappingsTypeName - No Substitution Mappings node defined"); + return null; + } + + return nodeType.getType(); + } + + @Override + //Sunny flow - covered with UT + public Metadata getServiceMetadata() { + return toscaTemplate.getMetaData(); + } + + @Override + //Sunny flow - covered with UT + public Map<String, Object> getServiceMetadataProperties() { + if (toscaTemplate.getMetaData() == null){ + return null; + } + return new HashMap<>(toscaTemplate.getMetaData().getAllProperties()); + } + + @Override + public Map<String, String> getServiceMetadataAllProperties() { + if (toscaTemplate.getMetaData() == null){ + return null; + } + return toscaTemplate.getMetaData().getAllProperties(); + } + + @Override + //Sunny flow - covered with UT + public List<Input> getServiceInputs() { + return toscaTemplate.getInputs(); + } + + @Override + //Sunny flow - covered with UT + public String getGroupPropertyLeafValue(Group group, String leafValuePath) { + if (group == null) { + log.error("getGroupPropertyLeafValue - group is null"); + return null; + } + + if (GeneralUtility.isEmptyString(leafValuePath)) { + log.error("getGroupPropertyLeafValue - leafValuePath is null or empty"); + return null; + } + + String[] split = getSplittedPath(leafValuePath); + LinkedHashMap<String, Property> properties = group.getProperties(); + Object property = PropertyUtils.processProperties(split, properties); + return property == null || property instanceof Function? null : String.valueOf(property); + } + + @Override + public Object getGroupPropertyAsObject(Group group, String leafValuePath) { + if (group == null) { + log.error("getGroupPropertyAsObject - group is null"); + return null; + } + + if (GeneralUtility.isEmptyString(leafValuePath)) { + log.error("getGroupPropertyAsObject - leafValuePath is null or empty"); + return null; + } + + String[] split = getSplittedPath(leafValuePath); + LinkedHashMap<String, Property> properties = group.getProperties(); + return PropertyUtils.processProperties(split, properties); + } + + @Override + //Sunny flow - covered with UT + public List<NodeTemplate> getCpListByVf(String vfCustomizationId) { + List<NodeTemplate> cpList = new ArrayList<>(); + if (GeneralUtility.isEmptyString(vfCustomizationId)) { + log.error("getCpListByVf vfCustomizationId string is empty"); + return cpList; + } + + List<NodeTemplate> serviceVfList = getServiceVfList(); + if (serviceVfList == null || serviceVfList.isEmpty()) { + log.error("getCpListByVf Vfs not exist for vfCustomizationId {}", vfCustomizationId); + return cpList; + } + NodeTemplate vfInstance = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationId); + if (vfInstance == null) { + log.debug("getCpListByVf vf list is null"); + return cpList; + } + cpList = getNodeTemplateBySdcType(vfInstance, SdcTypes.CP); + if (cpList == null || cpList.isEmpty()) + log.debug("getCpListByVf cps not exist for vfCustomizationId {}", vfCustomizationId); + return cpList; + } + + @Override + //Sunny flow - covered with UT + public List<NodeTemplate> getMembersOfVfModule(NodeTemplate vf, Group serviceLevelVfModule) { + if (vf == null) { + log.error("getMembersOfVfModule - vf is null"); + return new ArrayList<>(); + } + + if (serviceLevelVfModule == null || serviceLevelVfModule.getMetadata() == null || serviceLevelVfModule.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID) == null) { + log.error("getMembersOfVfModule - vfModule or its metadata is null. Cannot match a VF group based on invariantUuid from missing metadata."); + return new ArrayList<>(); + } + + + SubstitutionMappings substitutionMappings = vf.getSubMappingToscaTemplate(); + if (substitutionMappings != null) { + List<Group> groups = substitutionMappings.getGroups(); + if (groups != null) { + Optional<Group> findFirst = groups + .stream() + .filter(x -> (x.getMetadata() != null && serviceLevelVfModule.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID).equals(x.getMetadata().getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)))).findFirst(); + if (findFirst.isPresent()) { + List<String> members = findFirst.get().getMembers(); + if (members != null) { + return substitutionMappings.getNodeTemplates().stream().filter(x -> members.contains(x.getName())).collect(toList()); + } + } + } + } + return new ArrayList<>(); + } + + @Override + public List<Pair<NodeTemplate, NodeTemplate>> getNodeTemplatePairsByReqName( + List<NodeTemplate> listOfReqNodeTemplates, List<NodeTemplate> listOfCapNodeTemplates, String reqName) { + + if (listOfReqNodeTemplates == null) { + log.error("getNodeTemplatePairsByReqName - listOfReqNodeTemplates is null"); + return new ArrayList<>(); + } + + if (listOfCapNodeTemplates == null) { + log.error("getNodeTemplatePairsByReqName - listOfCapNodeTemplates is null"); + return new ArrayList<>(); + } + + if (GeneralUtility.isEmptyString(reqName)) { + log.error("getNodeTemplatePairsByReqName - reqName is null or empty"); + return new ArrayList<>(); + } + + List<Pair<NodeTemplate, NodeTemplate>> pairsList = new ArrayList<>(); + + for (NodeTemplate reqNodeTemplate : listOfReqNodeTemplates) { + List<RequirementAssignment> requirements = reqNodeTemplate.getRequirements().getRequirementsByName(reqName).getAll(); + for (RequirementAssignment reqEntry : requirements) { + String node = reqEntry.getNodeTemplateName(); + if (node != null) { + Optional<NodeTemplate> findFirst = listOfCapNodeTemplates.stream().filter(x -> x.getName().equals(node)).findFirst(); + if (findFirst.isPresent()) { + pairsList.add(new ImmutablePair<NodeTemplate, NodeTemplate>(reqNodeTemplate, findFirst.get())); + } + } + } + } + + return pairsList; + } + + @Override + //Sunny flow - covered with UT + public List<NodeTemplate> getAllottedResources() { + List<NodeTemplate> nodeTemplates = null; + nodeTemplates = toscaTemplate.getTopologyTemplate().getNodeTemplates(); + if (nodeTemplates.isEmpty()) { + log.error("getAllottedResources nodeTemplates not exist"); + } + nodeTemplates = nodeTemplates.stream().filter( + x -> x.getMetaData() != null && x.getMetaData().getValue("category").equals("Allotted Resource")) + .collect(toList()); + if (nodeTemplates.isEmpty()) { + log.debug("getAllottedResources - allotted resources not exist"); + } + return nodeTemplates; + } + + @Override + //Sunny flow - covered with UT + public String getTypeOfNodeTemplate(NodeTemplate nodeTemplate) { + if (nodeTemplate == null) { + + log.error("getTypeOfNodeTemplate nodeTemplate is null"); + return null; + } + return nodeTemplate.getTypeDefinition().getType(); + } + + /** + * This methdd is returning the csarConformanceLevel for input CSAR + * When csarConformanceLevel is configured with failOnError as False in Error Configuration; it + * assigns the default value to csarConformanceLevel which is the max level provided in + * Configuration file + * @return csarConformanceLevel + */ + @Override + public String getConformanceLevel() { + LinkedHashMap<String, Object> csarMeta = toscaTemplate.getMetaProperties("csar.meta"); + if (csarMeta == null){ + log.warn("No csar.meta file is found in CSAR - this file should hold the conformance level of the CSAR. This might be OK for older CSARs."); + if (configurationManager != null && !configurationManager.getErrorConfiguration() + .getErrorInfo("CONFORMANCE_LEVEL_ERROR").getFailOnError()){ + String csarConLevel = configurationManager.getConfiguration().getConformanceLevel().getMaxVersion(); + log.warn("csarConformanceLevel is not found in input csar; defaulting to max version {}" , csarConLevel); + return csarConLevel; + } + else { + log.warn("csarConformanceLevel is not found in input csar; returning null as no defaults defined in error configuration"); + return null; + } + } + + Object conformanceLevel = csarMeta.get("SDC-TOSCA-Definitions-Version"); + if (conformanceLevel != null){ + String confLevelStr = conformanceLevel.toString(); + log.debug("CSAR conformance level is {}", confLevelStr); + return confLevelStr; + } else { + log.error("Invalid csar.meta file - no entry found for SDC-TOSCA-Definitions-Version key. This entry should hold the conformance level."); + return null; + } + } + + + @Override + public String getNodeTemplateCustomizationUuid(NodeTemplate nt) { + String res = null; + if (nt != null && nt.getMetaData() != null){ + res = nt.getMetaData().getValue(CUSTOMIZATION_UUID); + } else { + log.error("Node template or its metadata is null"); + } + return res; + } + + public List<NodeTemplate> getNodeTemplateBySdcType(NodeTemplate parentNodeTemplate, SdcTypes sdcType) { + return getNodeTemplateBySdcType(parentNodeTemplate, sdcType, false); + } + + public boolean isNodeTypeSupported(NodeTemplate nodeTemplate) { + SdcTypes[] supportedTypes = SdcTypes.values(); + return Arrays.stream(supportedTypes) + .anyMatch(v->nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE) + .equals(v.getValue())); + } + + private List<NodeTemplate> getNodeTemplateBySdcType(NodeTemplate parentNodeTemplate, SdcTypes sdcType, boolean isVNF) { + + if (parentNodeTemplate == null) { + log.error("getNodeTemplateBySdcType - nodeTemplate is null or empty"); + return new ArrayList<>(); + } + + if (sdcType == null) { + log.error("getNodeTemplateBySdcType - sdcType is null or empty"); + return new ArrayList<>(); + } + + SubstitutionMappings substitutionMappings = parentNodeTemplate.getSubMappingToscaTemplate(); + + if (substitutionMappings != null) { + List<NodeTemplate> nodeTemplates = substitutionMappings.getNodeTemplates(); + if (nodeTemplates != null && !nodeTemplates.isEmpty()) { + if (sdcType.equals(SdcTypes.VFC) && isVNF) { + return nodeTemplates.stream() + .filter(x -> (x.getMetaData() != null && + sdcType.getValue().equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))) && isVNFType(x)) + .collect(toList()); + } + else { + return nodeTemplates.stream() + .filter(x -> (x.getMetaData() != null && + sdcType.getValue().equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE))) && !isVNFType(x)) + .collect(toList()); + } + } + else { + log.debug("getNodeTemplateBySdcType - SubstitutionMappings' node Templates not exist"); + } + } else + log.debug("getNodeTemplateBySdcType - SubstitutionMappings not exist"); + + return new ArrayList<>(); + } + + public Map<String, String> filterNodeTemplatePropertiesByValue(NodeTemplate nodeTemplate, FilterType filterType, String pattern) { + Map<String, String> filterMap = new HashMap<>(); + + if (nodeTemplate == null) { + log.error("filterNodeTemplatePropertiesByValue nodeTemplate is null"); + return filterMap; + } + + if (filterType == null) { + log.error("filterNodeTemplatePropertiesByValue filterType is null"); + return filterMap; + } + + if (GeneralUtility.isEmptyString(pattern)) { + log.error("filterNodeTemplatePropertiesByValue pattern string is empty"); + return filterMap; + } + + Map<String, Property> ntProperties = nodeTemplate.getProperties(); + + if (ntProperties != null && ntProperties.size() > 0) { + + for (Property current : ntProperties.values()) { + if (current.getValue() != null) { + filterProperties(current.getValue(), current.getName(), filterType, pattern, filterMap); + } + } + } + + log.trace("filterNodeTemplatePropertiesByValue - filterMap value: {}", filterMap); + + return filterMap; + } + + public NodeTemplate getVnfConfig(String vfCustomizationUuid) { + + if (GeneralUtility.isEmptyString(vfCustomizationUuid)) { + log.error("getVnfConfig - vfCustomizationId - is null or empty"); + return null; + } + + List<NodeTemplate> serviceVfList = getServiceVfList(); + NodeTemplate vfInstance = getNodeTemplateByCustomizationUuid(serviceVfList, vfCustomizationUuid); + return getNodeTemplateBySdcType(vfInstance, SdcTypes.VFC, true).stream().findAny().orElse(null); + } + + @Override + public boolean hasTopology(NodeTemplate nodeTemplate) { + if (nodeTemplate == null) { + log.error("hasTopology - nodeTemplate - is null"); + return false; + } + + if (nodeTemplate.getMetaData() != null) { + String type = nodeTemplate.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE); + log.debug("hasTopology - node template {} is a {} type", nodeTemplate.getName(), type); + return SdcTypes.isComplex(type); + } + + return false; + } + + @Override + public List<NodeTemplate> getNodeTemplateChildren(NodeTemplate nodeTemplate) { + if (nodeTemplate == null) { + log.error("getNodeTemplateChildren - nodeTemplate - is null"); + return new ArrayList<>(); + } + + SubstitutionMappings substitutionMappings = nodeTemplate.getSubMappingToscaTemplate(); + if (substitutionMappings != null) { + List<NodeTemplate> nodeTemplates = substitutionMappings.getNodeTemplates(); + if (nodeTemplates != null && !nodeTemplates.isEmpty()) { + + return nodeTemplates.stream() + .filter(x -> !isVNFType(x)) + .collect(toList()); + } + else { + log.debug("getNodeTemplateChildren - SubstitutionMappings' node Templates not exist"); + } + } else + log.debug("getNodeTemplateChildren - SubstitutionMappings not exist"); + + return new ArrayList<>(); + } + + @Override + public NodeTemplate getServiceNodeTemplateByNodeName(String nodeName) { + if (GeneralUtility.isEmptyString(nodeName)) { + log.error("getServiceNodeTemplateByNodeName - nodeName - is null or empty"); + return null; + } + + List<NodeTemplate> nodeTemplates = getServiceNodeTemplates(); + Optional<NodeTemplate> findFirst = nodeTemplates.stream().filter(nt -> nt.getName().equals(nodeName)).findFirst(); + + return findFirst.isPresent() ? findFirst.get() : null; + } + + @Override + public Metadata getNodeTemplateMetadata(NodeTemplate nt) { + if (nt == null) { + log.error("getNodeTemplateMetadata - nt (node template) - is null"); + return null; + } + + return nt.getMetaData(); + } + + @Override + public CapabilityAssignments getCapabilitiesOf(NodeTemplate nt) { + if (nt == null) { + log.error("getCapabilitiesOf - nt (node template) - is null"); + return null; + } + + return nt.getCapabilities(); + } + + @Override + public RequirementAssignments getRequirementsOf(NodeTemplate nt) { + if (nt == null) { + log.error("getRequirementsOf - nt (node template) - is null"); + return null; + } + + return nt.getRequirements(); + } + + @Override + public String getCapabilityPropertyLeafValue(CapabilityAssignment capability, String pathToPropertyLeafValue) { + if (capability == null) { + log.error("getCapabilityPropertyLeafValue - capability is null"); + return null; + } + + if (GeneralUtility.isEmptyString(pathToPropertyLeafValue)) { + log.error("getCapabilityPropertyLeafValue - pathToPropertyLeafValue is null or empty"); + return null; + } + + String[] split = getSplittedPath(pathToPropertyLeafValue); + LinkedHashMap<String, Property> properties = capability.getProperties(); + Object property = PropertyUtils.processProperties(split, properties); + return property == null || property instanceof Function ? null : String.valueOf(property); + } + + @Override + public ArrayList<Group> getGroupsOfOriginOfNodeTemplate(NodeTemplate nodeTemplate) { + if(StringUtils.isNotEmpty(nodeTemplate.getName())){ + return getNodeTemplateByName(nodeTemplate.getName()).getSubMappingToscaTemplate().getGroups(); + } + return new ArrayList<>(); + } + + @Override + public ArrayList<Group> getGroupsOfTopologyTemplateByToscaGroupType(String groupType) { + if(toscaTemplate.getGroups() == null) + return new ArrayList<>(); + return (ArrayList<Group>) toscaTemplate.getGroups() + .stream() + .filter(g->g.getType().equals(groupType)) + .sorted(Group::compareTo) + .collect(toList()); + } + + @Override + public ArrayList<Group> getGroupsOfTopologyTemplate() { + return toscaTemplate.getGroups() == null ? new ArrayList<>() : toscaTemplate.getGroups(); + } + + @Override + public ArrayList<Group> getGroupsOfOriginOfNodeTemplateByToscaGroupType(NodeTemplate nodeTemplate, String groupType) { + return (ArrayList<Group>) getGroupsOfOriginOfNodeTemplate(nodeTemplate) + .stream() + .filter(g->g.getType().equals(groupType)) + .sorted(Group::compareTo) + .collect(toList()); + } + + @Override + public List<NodeTemplate> getGroupMembersFromTopologyTemplate(String groupName) { + if(toscaTemplate.getNodeTemplates() == null){ + return new ArrayList<>(); + } + List<String> membersNames = getGroupMembers(groupName); + return toscaTemplate.getNodeTemplates().stream() + .filter(nt->membersNames.contains(nt.getName())) + .collect(toList()); + } + + + @Override + public List<NodeTemplate> getGroupMembersOfOriginOfNodeTemplate(NodeTemplate nodeTemplate, String groupName) { + ArrayList<Group> groups = getGroupsOfOriginOfNodeTemplate(nodeTemplate); + if(!groups.isEmpty()){ + Optional<Group> group = groups.stream().filter(g -> g.getName().equals(groupName)).findFirst(); + if(group.isPresent()){ + return nodeTemplate.getSubMappingToscaTemplate().getNodeTemplates().stream() + .filter(nt -> group.get().getMembers().contains(nt.getName())) + .collect(toList()); + } + } + return new ArrayList<>(); + } + + public List<NodeTemplate> getServiceNodeTemplateBySdcType(SdcTypes sdcType) { + if (sdcType == null) { + log.error("getServiceNodeTemplateBySdcType - sdcType is null or empty"); + return new ArrayList<>(); + } + + TopologyTemplate topologyTemplate = toscaTemplate.getTopologyTemplate(); + return getNodeTemplateBySdcType(topologyTemplate, sdcType); + } + + /************************************* helper functions ***********************************/ + private boolean isVNFType(NodeTemplate nt) { + return nt.getType().endsWith("VnfConfiguration"); + } + + @SuppressWarnings("unchecked") + private Map<String, String> filterProperties(Object property, String path, FilterType filterType, String pattern, Map<String, String> filterMap) { + + if (property instanceof Map) { + for (Map.Entry<String, Object> item: ((Map<String, Object>) property).entrySet()) { + String itemPath = path + PATH_DELIMITER + item.getKey(); + filterProperties(item.getValue(), itemPath, filterType, pattern, filterMap); + } + } else if (property instanceof List) { + for (Object item: (List<Object>)property) { + filterProperties(item, path, filterType, pattern, filterMap); + } + } else { + if (filterType.isMatch(property.toString(), pattern)) { + filterMap.put(path, property.toString()); + } + } + + return filterMap; + } + + /************************************* helper functions ***********************************/ + private List<NodeTemplate> getNodeTemplateBySdcType(TopologyTemplate topologyTemplate, SdcTypes sdcType) { + if (sdcType == null) { + log.error("getNodeTemplateBySdcType - sdcType is null or empty"); + return new ArrayList<>(); + } + + if (topologyTemplate == null) { + log.error("getNodeTemplateBySdcType - topologyTemplate is null"); + return new ArrayList<>(); + } + + List<NodeTemplate> nodeTemplates = topologyTemplate.getNodeTemplates(); + + if (nodeTemplates != null && !nodeTemplates.isEmpty()) + return nodeTemplates.stream().filter(x -> (x.getMetaData() != null && sdcType.getValue().equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_TYPE)))).collect(toList()); + + log.debug("getNodeTemplateBySdcType - topologyTemplate's nodeTemplates not exist"); + return new ArrayList<>(); + } + + //Assumed to be unique property for the list + private NodeTemplate getNodeTemplateByCustomizationUuid(List<NodeTemplate> nodeTemplates, String customizationId) { + if (customizationId != null) { + Optional<NodeTemplate> findFirst = nodeTemplates.stream().filter(x -> (x.getMetaData() != null && customizationId.equals(x.getMetaData().getValue(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID)))).findFirst(); + return findFirst.isPresent() ? findFirst.get() : null; + } + else { + log.error("getNodeTemplateByCustomizationUuid - customizationId is null"); + return null; + } + } + + @Override + public Map<String, List<InterfacesDef>> getInterfacesOf(NodeTemplate nt){ + if (nt == null) { + return null; + } + return nt.getAllInterfaceDetailsForNodeType(); + } + + @Override + public List<String> getInterfaces(NodeTemplate nt){ + Map<String, List<InterfacesDef>> interfaceDetails = nt.getAllInterfaceDetailsForNodeType(); + return new ArrayList<>(interfaceDetails.keySet()); + } + + @Override + public List<InterfacesDef> getInterfaceDetails(NodeTemplate nt, String interfaceName){ + Map<String, List<InterfacesDef>> interfaceDetails = nt.getAllInterfaceDetailsForNodeType(); + return interfaceDetails.get(interfaceName); + } + + @Override + public List<String> getAllInterfaceOperations(NodeTemplate nt, String interfaceName){ + Map<String, List<InterfacesDef>> interfaceDetails = nt.getAllInterfaceDetailsForNodeType(); + return interfaceDetails.values().stream().flatMap(List::stream).map(val -> val.getOperationName()).collect( + Collectors.toList()); + } + + @Override + public InterfacesDef getInterfaceOperationDetails(NodeTemplate nt, String interfaceName, String operationName){ + Map<String, List<InterfacesDef>> interfaceDetails = nt.getAllInterfaceDetailsForNodeType(); + if(!interfaceDetails.isEmpty()){ + List<InterfacesDef> interfaceDefs = interfaceDetails.get(interfaceName); + return interfaceDefs.stream().filter(val -> val.getOperationName().equals(operationName)).findFirst().orElse(null); + } + return null; + } + + @Override + public List<String> getPropertyLeafValueByPropertyNamePathAndNodeTemplatePath(String propertyNamePath, String nodeTemplatePath) { + log.info("A new request is received: property path is [{}], node template path is [{}]", + propertyNamePath, nodeTemplatePath); + + List<String> propertyValuesList; + + if (StringUtils.isEmpty(nodeTemplatePath) || StringUtils.isEmpty(propertyNamePath)) { + log.error("One of parameters is empty or null: property path is [{}], node template path is [{}]", + propertyNamePath, nodeTemplatePath); + propertyValuesList = Collections.emptyList(); + } + else { + String[] nodeTemplates = getSplittedPath(nodeTemplatePath); + propertyValuesList = getPropertyFromInternalNodeTemplate(getNodeTemplateByName(nodeTemplates[0]), 1, nodeTemplates, propertyNamePath); + log.info("Found property value {} by path [{}] for node template [{}]", + propertyValuesList, propertyNamePath, nodeTemplatePath); + } + return propertyValuesList; + } + + private List<String> getPropertyFromInternalNodeTemplate(NodeTemplate parent, int index, + String[] nodeTemplatePath, String propertyPath) { + List<String> propertyValuesList; + if (parent == null) { + log.error("Node template {} is not found, the request will be rejected", nodeTemplatePath[index]); + propertyValuesList = Collections.emptyList(); + } + else if (nodeTemplatePath.length <= index) { + log.debug("Stop NODE TEMPLATE searching"); + propertyValuesList = getSimpleOrListPropertyValue(parent, propertyPath); + } + else { + log.debug("Node template {} is found with name {}", nodeTemplatePath[index], parent.getName()); + NodeTemplate childNT = getChildNodeTemplateByName(parent, nodeTemplatePath[index]); + + if (childNT == null || !isNodeTypeSupported(childNT)) { + log.error("Unsupported or not found node template named {}, the request will be rejected", + nodeTemplatePath[index]); + propertyValuesList = Collections.emptyList(); + } + else { + propertyValuesList = getPropertyFromInternalNodeTemplate(childNT, index + 1, nodeTemplatePath, + propertyPath); + } + } + return propertyValuesList; + } + + + + private List<String> getSimpleOrListPropertyValue(NodeTemplate nodeTemplate, String propertyPath) { + List<String> propertyValueList; + String[] path = getSplittedPath(propertyPath); + Property property = getNodeTemplatePropertyObjectByName(nodeTemplate, path[0]); + + if (PropertyUtils.isPropertyTypeSimpleOrListOfSimpleTypes(nodeTemplate, path, property)) { + //the requested property type is either simple or list of simple types + PropertySchemaType propertyType = PropertySchemaType.getEnumByValue(property.getType()); + if (propertyType == PropertySchemaType.LIST && + PropertyUtils.isDataPropertyType((String)property.getEntrySchema() + .get(SdcPropertyNames.PROPERTY_NAME_TYPE))) { + //cover the case when a type of property "path[0]' is list of data types + // and the requested property is an internal simple property of this data type + propertyValueList = calculatePropertyValue(getNodeTemplatePropertyValueAsObject(nodeTemplate, path[0]), path, nodeTemplate.getName()); + } + else { + //the requested property is simple type or list of simple types + propertyValueList = calculatePropertyValue(getNodeTemplatePropertyValueAsObject(nodeTemplate, propertyPath), null, nodeTemplate.getName()); + } + } + else { + log.error("The type of property {} on node {} is neither simple nor list of simple objects, the request will be rejected", + propertyPath, nodeTemplate.getName()); + propertyValueList = Collections.emptyList(); + } + return propertyValueList; + } + + private List<String> calculatePropertyValue(Object valueAsObject, String path[], String nodeName) { + if (valueAsObject == null || valueAsObject instanceof Map) { + log.error("The property {} either is not found on node template [{}], or it is data type, or it is not resolved get_input", path, nodeName); + return Collections.emptyList(); + } + if (path != null) { + return PropertyUtils.findSimplePropertyValueInListOfDataTypes((List<Object>)valueAsObject, path); + } + return PropertyUtils.buildSimplePropertValueOrList(valueAsObject); + } + + + + + private Property getNodeTemplatePropertyObjectByName(NodeTemplate nodeTemplate, String propertyName) { + return nodeTemplate.getPropertiesObjects() + .stream() + .filter(p->p.getName().equals(propertyName)) + .findFirst() + .orElse(null); + } + + private NodeTemplate getChildNodeTemplateByName(NodeTemplate parent, String nodeTemplateName) { + return getNodeTemplateChildren(parent) + .stream() + .filter(nt->nt.getName().equals(nodeTemplateName)) + .findFirst().orElse(null); + } + + @Override + public List<Input> getInputsWithAnnotations() { + return toscaTemplate.getInputs(true); + } + + @Override + public List<IEntityDetails> getEntity(EntityQuery entityQuery, TopologyTemplateQuery topologyTemplateQuery, boolean isRecursive) { + + if (log.isDebugEnabled()) { + log.debug("getEntity request: EntityQuery <{}>, TopologyTemplateQuery <{}>, isRecursive<{}>", + entityQuery, topologyTemplateQuery, isRecursive); + } + return new QueryProcessor(toscaTemplate, entityQuery, topologyTemplateQuery, isRecursive).doQuery(); + } + + @Override + public HashSet<DataType> getDataTypes() { + return toscaTemplate.getDataTypes(); + } + + } diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/SdcPropertyNames.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/SdcPropertyNames.java new file mode 100644 index 0000000..0884281 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/SdcPropertyNames.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.impl; + +public class SdcPropertyNames { + public static final String PROPERTY_NAME_INVARIANTUUID = "invariantUUID"; + public static final String PROPERTY_NAME_UUID = "UUID"; + public static final String PROPERTY_NAME_CUSTOMIZATIONUUID = "customizationUUID"; + public static final String PROPERTY_NAME_VERSION = "version"; + + //Groups metadata + public static final String PROPERTY_NAME_VFMODULEMODELINVARIANTUUID = "vfModuleModelInvariantUUID"; + public static final String PROPERTY_NAME_VFMODULEMODELUUID = "vfModuleModelUUID"; + public static final String PROPERTY_NAME_VFMODULECUSTOMIZATIONUUID = "vfModuleCustomizationUUID"; + public static final String PROPERTY_NAME_VFMODULEMODELVERSION = "vfModuleModelVersion"; + public static final String PROPERTY_NAME_VFMODULEMODELNAME = "vfModuleModelName"; + + //Groups properties + public static final String PROPERTY_NAME_VFMODULETYPE = "vf_module_type"; + public static final String PROPERTY_NAME_VFMODULELABEL = "vf_module_label"; + public static final String PROPERTY_NAME_MINVFMODULEINSTANCES = "min_vf_module_instances"; + public static final String PROPERTY_NAME_MAXVFMODULEINSTANCES = "max_vf_module_instances"; + public static final String PROPERTY_NAME_INITIALCOUNT = "initial_count"; + + + public static final String PROPERTY_NAME_DESCRIPTION = "description"; + public static final String PROPERTY_NAME_TYPE = "type"; + public static final String PROPERTY_NAME_CATEGORY = "category"; + public static final String PROPERTY_NAME_SUBCATEGORY = "subcategory"; + public static final String PROPERTY_NAME_RESOURCEVENDOR = "resourceVendor"; + public static final String PROPERTY_NAME_RESOURCEVENDORRELEASE = "resourceVendorRelease"; + //VFC + public static final String PROPERTY_NAME_NFCCODE = "nfc_code"; + public static final String PROPERTY_NAME_VMTYPETAG = "vm_type_tag"; + public static final String PROPERTY_NAME_VMTYPE = "vm_type"; + public static final String PROPERTY_NAME_VFCNAMING_ECOMPGENERATEDNAMING="vfc_naming#ecomp_generated_naming"; + public static final String PROPERTY_NAME_VFCNAMING_NAMINGPOLICY="vfc_naming#naming_policy"; + //VF + public static final String PROPERTY_NAME_NFTYPE = "nf_type"; + public static final String PROPERTY_NAME_NFROLE = "nf_role"; + public static final String PROPERTY_NAME_NFFUNCTION = "nf_function"; + public static final String PROPERTY_NAME_NFCODE = "nf_code"; + public static final String PROPERTY_NAME_MININSTANCES = "min_instances"; + public static final String PROPERTY_NAME_MAXINSTANCES = "max_instances"; + public static final String PROPERTY_NAME_AVAILABILITYZONEMAXCOUNT = "availability_zone_max_count"; + public static final String PROPERTY_NAME_AVAILABILITYZONECOUNT = "availability_zone_count"; + public static final String PROPERTY_NAME_NAME = "name"; + public static final String PROPERTY_NAME_VNFECOMPNAMING_ECOMPGENERATEDNAMING="vnf_ecomp_naming#ecomp_generated_naming"; + public static final String PROPERTY_NAME_VNFECOMPNAMING_NAMINGPOLICY="vnf_ecomp_naming#naming_policy"; + public static final String PROPERTY_NAME_ECOMPGENERATEDVMASSIGNMENTS = "ecomp_generated_vm_assignments"; + //Service + public static final String PROPERTY_NAME_SERVICENAMING_DEFAULT_ECOMPGENERATEDNAMING="service_naming#default#ecomp_generated_naming"; + public static final String PROPERTY_NAME_SERVICENAMING_DEFAULT_NAMINGPOLICY="service_naming#default#naming_policy"; + //VL + public static final String PROPERTY_NAME_NETWORKTYPE="network_type"; + public static final String PROPERTY_NAME_NETWORKROLE="network_role"; + public static final String PROPERTY_NAME_NETWORKROLETAG="network_role_tag"; + public static final String PROPERTY_NAME_NETWORKTECHNOLOGY="network_technology"; + public static final String PROPERTY_NAME_NETWORKSCOPE="network_scope"; + public static final String PROPERTY_NAME_NETWORKECOMPNAMING_ECOMPGENERATEDNAMING="network_ecomp_naming#ecomp_generated_naming"; + public static final String PROPERTY_NAME_NETWORKECOMPNAMING_NAMINGPOLICY="network_ecomp_naming#naming_policy"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_ISSHAREDNETWORK="network_assignments#is_shared_network"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_ISEXTERNALNETWORK="network_assignments#is_external_network"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_ECOMPGENERATEDNETWORKASSIGNMENT="network_assignments#ecomp_generated_network_assignment"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_USEIPV4="network_assignments#ipv4_subnet_default_assignments#use_ipv4"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_IPNETWORKADDRESSPLAN="network_assignments#ipv4_subnet_default_assignments#ip_network_address_plan"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_DHCPENABLED="network_assignments#ipv4_subnet_default_assignments#dhcp_enabled"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_IPVERSION="network_assignments#ipv4_subnet_default_assignments#ip_version"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_CIDRMASK="network_assignments#ipv4_subnet_default_assignments#cidr_mask"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV4SUBNETDEFAULTASSIGNMENTS_MINSUBNETSCOUNT="network_assignments#ipv4_subnet_default_assignments#min_subnets_count"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_USEIPV6="network_assignments#ipv6_subnet_default_assignments#use_ipv6"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_IPNETWORKADDRESSPLAN="network_assignments#ipv6_subnet_default_assignments#ip_network_address_plan"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_DHCPENABLED="network_assignments#ipv6_subnet_default_assignments#dhcp_enabled"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_IPVERSION="network_assignments#ipv6_subnet_default_assignments#ip_version"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_CIDRMASK="network_assignments#ipv6_subnet_default_assignments#cidr_mask"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_IPV6SUBNETDEFAULTASSIGNMENTS_MINSUBNETSCOUNT="network_assignments#ipv6_subnet_default_assignments#min_subnets_count"; + + /*public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_PROVIDERNETWORK_ISPROVIDERNETWORK="network_assignments#provider_network#is_provider_network"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_PROVIDERNETWORK_PHYSICALNETWORKNAME="network_assignments#provider_network#physical_network_name"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_PROVIDERNETWORK_NUMA="network_assignments#provider_network#numa"; + public static final String PROPERTY_NAME_NETWORKASSIGNMENTS_PROVIDERNETWORK_PNICINSTANCE="network_assignments#provider_network#pnic_instance"; + */ + + public static final String PROPERTY_NAME_PROVIDERNETWORK_ISPROVIDERNETWORK="provider_network#is_provider_network"; + public static final String PROPERTY_NAME_PROVIDERNETWORK_PHYSICALNETWORKNAME="provider_network#physical_network_name"; + public static final String PROPERTY_NAME_PROVIDERNETWORK_NUMA="provider_network#numa"; + public static final String PROPERTY_NAME_PROVIDERNETWORK_PNICINSTANCE="provider_network#pnic_instance"; + + public static final String PROPERTY_NAME_NETWORKFLOWS_ISBOUNDTOVPN="network_flows#is_bound_to_vpn"; + public static final String PROPERTY_NAME_NETWORKFLOWS_VPNBINDING="network_flows#vpn_binding"; + + //Policy + public static final String PROPERTY_NAME_TOPOLOGY_TEMPLATE = "topology_template"; + public static final String PROPERTY_NAME_NODE_TEMPLATES = "node_templates"; + public static final String PROPERTY_NAME_POLICIES = "policies"; + public static final String PROPERTY_NAME_GROUPS = "groups"; + public static final String PROPERTY_NAME_METADATA = "metadata"; + public static final String PROPERTY_NAME_PROPERTIES = "properties"; + public static final String PROPERTY_NAME_TARGETS = "targets"; + public static final String PROPERTY_NAME_MEMBERS = "members"; + public static final String PROPERTY_NAME_CAPABILITIES = "capabilities"; + public static final String PROPERTY_NAME_ENTRY_SCHEMA = "entry_schema"; +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/SdcToscaParserFactory.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/SdcToscaParserFactory.java new file mode 100644 index 0000000..e24a231 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/impl/SdcToscaParserFactory.java @@ -0,0 +1,222 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.sdc.tosca.parser.api.ConformanceLevel; +import org.onap.sdc.tosca.parser.config.ConfigurationManager; +import org.onap.sdc.tosca.parser.config.ErrorInfo; +import org.onap.sdc.tosca.parser.config.JToscaValidationIssueInfo; +import org.onap.sdc.tosca.parser.config.SdcToscaParserErrors; +import org.onap.sdc.tosca.parser.enums.JToscaValidationIssueType; +import org.onap.sdc.tosca.parser.utils.GeneralUtility; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.sdc.toscaparser.api.ToscaTemplate; +import org.onap.sdc.toscaparser.api.common.JToscaValidationIssue; +import org.onap.sdc.toscaparser.api.common.JToscaException; +import org.onap.sdc.toscaparser.api.utils.JToscaErrorCodes; +import org.onap.sdc.toscaparser.api.utils.ThreadLocalsHolder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SdcToscaParserFactory { + private static Logger log = LoggerFactory.getLogger(SdcToscaParserFactory.class.getName()); + + private static ConfigurationManager configurationManager; + private static volatile SdcToscaParserFactory instance; + private List<JToscaValidationIssue> criticalExceptions = new ArrayList<>(); + private List<JToscaValidationIssue> warningExceptions = new ArrayList<>(); + private List<JToscaValidationIssue> notAnalyzadExceptions = new ArrayList<>(); + private SdcToscaParserFactory() {} + + /** + * Get an SdcToscaParserFactory instance. + * @return SdcToscaParserFactory instance. + */ + public static SdcToscaParserFactory getInstance() { + if (instance == null) { + synchronized (SdcToscaParserFactory.class) { + if (instance == null) { + instance = new SdcToscaParserFactory(); + configurationManager = ConfigurationManager.getInstance(); + } + } + } + return instance; + } + + public static void setConfigurationManager(ConfigurationManager configurationManager) { + SdcToscaParserFactory.configurationManager = configurationManager; + } + + /** + * Get an ISdcCsarHelper object for this CSAR file. + * + * @param csarPath - the absolute path to CSAR file. + * @return ISdcCsarHelper object. + * @throws SdcToscaParserException - in case the path or CSAR are invalid. + */ + public ISdcCsarHelper getSdcCsarHelper(String csarPath) throws SdcToscaParserException { + return init(csarPath, true); + } + + /** + * Get an ISdcCsarHelper object for this CSAR file. + * + * @param csarPath - the absolute path to CSAR file. + * @param resolveGetInput - resolve get_input properties + * @return ISdcCsarHelper object. + * @throws SdcToscaParserException - in case the path or CSAR are invalid. + */ + public ISdcCsarHelper getSdcCsarHelper(String csarPath, boolean resolveGetInput) throws SdcToscaParserException { + return init(csarPath, resolveGetInput); + } + + private ISdcCsarHelper init(String csarPath, boolean resolveGetInput) throws SdcToscaParserException { + synchronized (SdcToscaParserFactory.class) { + ToscaTemplate tosca = null; + try { + tosca = new ToscaTemplate(csarPath, null, true, null, resolveGetInput); + } catch (JToscaException e) { + throwSdcToscaParserException(e); + } + SdcCsarHelperImpl sdcCsarHelperImpl = new SdcCsarHelperImpl(tosca, configurationManager); + String cSarConformanceLevel = sdcCsarHelperImpl.getConformanceLevel(); + validateCsarVersion(cSarConformanceLevel); + try { + handleErrorsByTypes(csarPath, cSarConformanceLevel); + } catch (JToscaException e) { + throwSdcToscaParserException(e); + } + return sdcCsarHelperImpl; + } + } + + private void handleErrorsByTypes(String csarPath, String cSarConformanceLevel) throws JToscaException { + clearValidationIssuesLists(); + for(JToscaValidationIssue toscaValidationIssue : ThreadLocalsHolder.getCollector().getValidationIssues().values()){ + List<JToscaValidationIssueInfo> issueInfos = configurationManager.getJtoscaValidationIssueConfiguration().getValidationIssues().get(toscaValidationIssue.getCode()); + if(issueInfos != null && !issueInfos.isEmpty()){ + JToscaValidationIssueInfo issueInfo = null; + issueInfo = issueInfos.stream() + .filter(i-> isMatchConformanceLevel(cSarConformanceLevel,i.getSinceCsarConformanceLevel())) + .max((i1,i2) -> GeneralUtility.conformanceLevelCompare(i1.getSinceCsarConformanceLevel(), i2.getSinceCsarConformanceLevel()) ) + .orElse(null); + + if(issueInfo != null){ + switch (JToscaValidationIssueType.valueOf(issueInfo.getIssueType())) { + case CRITICAL: + criticalExceptions.add(toscaValidationIssue); + break; + case WARNING: + warningExceptions.add(toscaValidationIssue); + break; + default: + break; + } + }else{ + notAnalyzadExceptions.add(toscaValidationIssue); + } + }else{//notAnalyzed + notAnalyzadExceptions.add(toscaValidationIssue); + } + } + logErrors(csarPath); + } + + private void clearValidationIssuesLists(){ + notAnalyzadExceptions.clear(); + criticalExceptions.clear(); + warningExceptions.clear(); + } + + private void logErrors(String inputPath) throws JToscaException{ + //Warnings + int warningsCount = warningExceptions.size(); + if (warningsCount > 0) { + log.warn("####################################################################################################"); + log.warn("CSAR Warnings found! CSAR name - {}", inputPath); + log.warn("ToscaTemplate - verifyTemplate - {} Parsing Warning{} occurred...", warningsCount, (warningsCount > 1 ? "s" : "")); + for (JToscaValidationIssue info : warningExceptions) { + log.warn("JTosca Exception [{}]: {}. CSAR name - {}", info.getCode(),info.getMessage(), inputPath); + } + log.warn("####################################################################################################"); + } + //Criticals + int criticalsCount = criticalExceptions.size(); + if (criticalsCount > 0) { + log.error("####################################################################################################"); + log.error("ToscaTemplate - verifyTemplate - {} Parsing Critical{} occurred...", criticalsCount, (criticalsCount > 1 ? "s" : "")); + for (JToscaValidationIssue info : criticalExceptions) { + log.error("JTosca Exception [{}]: {}. CSAR name - {}", info.getCode(),info.getMessage(), inputPath); + } + throw new JToscaException(String.format("CSAR Validation Failed. CSAR name - {}. Please check logs for details.", inputPath), JToscaErrorCodes.CSAR_TOSCA_VALIDATION_ERROR.getValue()); + } + } + public List<JToscaValidationIssue> getCriticalExceptions() { + return criticalExceptions; + } + + public List<JToscaValidationIssue> getWarningExceptions() { + return warningExceptions; + } + + public List<JToscaValidationIssue> getNotAnalyzadExceptions() { + return notAnalyzadExceptions; + } + + + private void validateCsarVersion(String cSarVersion) throws SdcToscaParserException { + ConformanceLevel level = configurationManager.getConfiguration().getConformanceLevel(); + String minVersion = level.getMinVersion(); + if (cSarVersion != null) { + if (GeneralUtility.conformanceLevelCompare(cSarVersion, minVersion) < 0) { + throwConformanceLevelException(minVersion); + } + } else { + throwConformanceLevelException(minVersion); + } + } + + private boolean isMatchConformanceLevel(String ValidationIssueVersion, String cSarVersion){ + if (ValidationIssueVersion != null && cSarVersion != null) { + if ((GeneralUtility.conformanceLevelCompare(ValidationIssueVersion, cSarVersion) >= 0)) { + return true; + } + } + return false; + } + private void throwConformanceLevelException(String minVersion) throws SdcToscaParserException { + ErrorInfo errorInfo = configurationManager.getErrorConfiguration().getErrorInfo(SdcToscaParserErrors.CONFORMANCE_LEVEL_ERROR.toString()); + throw new SdcToscaParserException(String.format(errorInfo.getMessage(), minVersion), errorInfo.getCode()); + } + + private void throwSdcToscaParserException(JToscaException e) throws SdcToscaParserException { + ErrorInfo errorInfo = configurationManager.getErrorConfiguration().getErrorInfo(SdcToscaParserErrors.getSdcErrorByJToscaError(JToscaErrorCodes.getByCode(e.getCode())).toString()); + throw new SdcToscaParserException(errorInfo.getMessage(), errorInfo.getCode()); + } + + + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/GeneralUtility.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/GeneralUtility.java new file mode 100644 index 0000000..02995a2 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/GeneralUtility.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.utils; + +import java.util.Arrays; + +public class GeneralUtility { + + public static boolean isEmptyString(String str) { + return str == null || str.trim().isEmpty(); + } + + + /** + * Compares two version strings. + * <p> + * Use this instead of String.compareTo() for a non-lexicographical + * comparison that works for version strings. e.g. "1.10".compareTo("1.6"). + * + * @param str1 a string of ordinal numbers separated by decimal points. + * @param str2 a string of ordinal numbers separated by decimal points. + * @return The result is a negative integer if str1 is _numerically_ less than str2. + * The result is a positive integer if str1 is _numerically_ greater than str2. + * The result is zero if the strings are _numerically_ equal. + * It does not work if "1.10" is supposed to be equal to "1.10.0". + */ + public static int conformanceLevelCompare(String str1, String str2) { + String[] vals1 = str1.split("\\."); + String[] vals2 = str2.split("\\."); + int i = 0; + // set index to first non-equal ordinal or length of shortest version string + while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) { + i++; + } + // compare first non-equal ordinal number + if (i < vals1.length && i < vals2.length) { + int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i])); + return Integer.signum(diff); + } + //in case of 0 after the . e.g: "3" = "3.0" or "3.0.0.0" = "3.0" + str2 = str2.substring(i).replace(".", ""); + str1 = str1.substring(i).replace(".", ""); + if ((!(str1.equals(""))) && Integer.valueOf(str1) == 0){ + vals1 = Arrays.copyOf(vals1, i); + } + if ((!(str2.equals(""))) && Integer.valueOf(str2) == 0){ + vals2 = Arrays.copyOf(vals2, i); + } + + // the strings are equal or one string is a substring of the other + // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" + return Integer.signum(vals1.length - vals2.length); + } + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/PropertyUtils.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/PropertyUtils.java new file mode 100644 index 0000000..e150d75 --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/PropertyUtils.java @@ -0,0 +1,192 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.utils; + +import com.google.common.collect.Lists; +import org.onap.sdc.tosca.parser.enums.PropertySchemaType; +import org.onap.sdc.tosca.parser.impl.SdcPropertyNames; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.Property; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.onap.sdc.tosca.parser.enums.PropertySchemaType.PropertySchemaComplexity.Simple; + +public class PropertyUtils { + + private static Logger log = LoggerFactory.getLogger(PropertyUtils.class.getName()); + + private PropertyUtils() {} + + private static String calculatePropertyType(LinkedHashMap<String, Object> property) { + String type = (String) property.get(SdcPropertyNames.PROPERTY_NAME_TYPE); + if (PropertySchemaType.LIST.getSchemaTypeName().equals(type)) { + //it might be a data type + return getEntrySchemaType(property); + } + return type; + } + + private static String getEntrySchemaType(LinkedHashMap<String, Object> property) { + LinkedHashMap<String, Object> entrySchema = (LinkedHashMap<String, Object>)property.get(SdcPropertyNames.PROPERTY_NAME_ENTRY_SCHEMA); + if (entrySchema != null) { + return (String) entrySchema.get(SdcPropertyNames.PROPERTY_NAME_TYPE); + } + return null; + } + + private static String calculatePropertyType(Property property) { + if (PropertySchemaType.LIST.getSchemaTypeName().equals(property.getType())) { + //if it is list, return entry schema type + return (String)property.getEntrySchema().get(SdcPropertyNames.PROPERTY_NAME_TYPE); + } + return property.getType(); + } + + public static boolean isListOfSimpleTypes(String type) { + PropertySchemaType entrySchemaType = PropertySchemaType.getEnumByValue(type); + return entrySchemaType.getSchemaTypeComplexity() == PropertySchemaType.PropertySchemaComplexity.Simple; + } + + public static boolean isDataPropertyType(String type) { + PropertySchemaType entrySchemaType = PropertySchemaType.getEnumByValue(type); + return entrySchemaType == PropertySchemaType.DATATYPE; + } + + public static Object processProperties(String[] split, LinkedHashMap<String, Property> properties) { + Optional<Map.Entry<String, Property>> findFirst = properties.entrySet().stream().filter(x -> x.getKey().equals(split[0])).findFirst(); + if (findFirst.isPresent()) { + Property property = findFirst.get().getValue(); + Object current = property.getValue(); + return iterateProcessPath(1, current, split); + } + String propName = (split != null && split.length > 0 ? split[0] : null); + log.error("processProperties - property {} is not found", propName); + return null; + } + + public static List<String> findSimplePropertyValueInListOfDataTypes(List<Object> valueAsObjectList, String[] path) { + return valueAsObjectList.stream() + .map(v->iterateProcessPath(1, v, path)) + .filter(Objects::nonNull) + .map(String::valueOf) + .collect(Collectors.toList()); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static Object iterateProcessPath(Integer index, Object current, String[] split) { + if (current == null) { + log.error("iterateProcessPath - this input has no default"); + return null; + } + if (split.length > index) { + for (int i = index; i < split.length; i++) { + if (current instanceof Map) { + current = ((Map<String, Object>) current).get(split[i]); + } else if (current instanceof List) { + current = ((List) current).get(0); + i--; + } + else { + log.error("iterateProcessPath - found an unexpected leaf where expected to find a complex type"); + return null; + } + } + } + if (current != null) { + return current; + } + log.error("iterateProcessPath - Path not Found"); + return null; + } + + public static boolean isPropertyTypeSimpleOrListOfSimpleTypes(NodeTemplate nodeTemplate, String[] path, Property property) { + PropertySchemaType internalPropertyType = PropertyUtils.getPropertyTypeByPath(nodeTemplate, path, property); + return internalPropertyType.getSchemaTypeComplexity() == Simple; + } + + private static PropertySchemaType getPropertyTypeByPath(NodeTemplate nodeTemplate, String[] path, Property property) { + String propertyType = calculatePropertyType(property); + String propertyTypeByPath = propertyType; + + if (path.length > 1) { + propertyTypeByPath = getInternalPropertyType(nodeTemplate, propertyType, path, 1); + } + return PropertySchemaType.getEnumByValue(propertyTypeByPath); + } + + public static List<String> buildSimplePropertValueOrList(Object value) { + if (value instanceof List) { + return ((ArrayList<Object>) value) + .stream() + //it might be null when get_input can't be resolved + // e.g.: + // - get_input has two parameters: 1. list and 2. index in this list + //and list has no value + // - neither value no default is defined for get_input + .filter(Objects::nonNull) + .map(String::valueOf) + .collect(Collectors.toList()); + } + return Lists.newArrayList(String.valueOf(value)); + } + + private static String getInternalPropertyType(NodeTemplate nodeTemplate, String dataTypeName, String[] path, int index) { + if (path.length > index) { + LinkedHashMap<String, Object> complexProperty = (LinkedHashMap<String, Object>) nodeTemplate.getCustomDef().get(dataTypeName); + if (complexProperty != null) { + LinkedHashMap<String, Object> properties = (LinkedHashMap<String, Object>) complexProperty.get(SdcPropertyNames.PROPERTY_NAME_PROPERTIES); + return getPropertyTypeFromCustomDef(nodeTemplate, path, index, properties); + } + } + //stop searching - seems as wrong flow: the path is finished but the value is not found yet + log.error("The property path {} is incorrect, the request will be rejected", path); + return null; + } + + private static String getPropertyTypeFromCustomDef(NodeTemplate nodeTemplate, String[] path, int index, LinkedHashMap<String, Object> properties) { + final String methodName = "getPropertyTypeFromCustomDef"; + if (properties != null) { + LinkedHashMap<String, Object> foundProperty = (LinkedHashMap<String, Object>) (properties).get(path[index]); + if (foundProperty != null) { + String propertyType = calculatePropertyType(foundProperty); + log.info("{} - type {} is data type", methodName, propertyType); + if ((index == path.length - 1)){ + log.info("{} - the last element {} in the property path is found", methodName, path[index]); + return propertyType; + } + return getInternalPropertyType(nodeTemplate, propertyType, path, index + 1); + } + log.error("{} - the property [{}] is not found", methodName, path[index]); + } + return null; + } + + +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/SdcToscaUtility.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/SdcToscaUtility.java new file mode 100644 index 0000000..ff3a31c --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/SdcToscaUtility.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.utils; + +import java.util.regex.Pattern; + +public class SdcToscaUtility { + + public final static Pattern COMPONENT_INSTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); + + public static String normaliseComponentInstanceName(String name) { + String normalizedName = name.toLowerCase(); + normalizedName = COMPONENT_INSTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); + String[] split = normalizedName.split(" "); + StringBuffer sb = new StringBuffer(); + for (String splitElement : split) { + sb.append(splitElement); + } + return sb.toString(); + } +} diff --git a/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/YamlToObjectConverter.java b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/YamlToObjectConverter.java new file mode 100644 index 0000000..86ecb9f --- /dev/null +++ b/sdc-tosca/src/main/java/org/onap/sdc/tosca/parser/utils/YamlToObjectConverter.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-tosca + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.tosca.parser.utils; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; + +public class YamlToObjectConverter { + + private static Logger log = LoggerFactory + .getLogger(YamlToObjectConverter.class.getName()); + + private static HashMap<String, Yaml> yamls = new HashMap<String, Yaml>(); + + private static Yaml defaultYaml = new Yaml(); + + private static <T> Yaml getYamlByClassName(Class<T> className) { + + Yaml yaml = yamls.get(className.getName()); + if (yaml == null) { + yaml = defaultYaml; + } + + return yaml; + } + + public <T> T convert(String dirPath, Class<T> className, + String configFileName) { + + T config = null; + + try { + + String fullFileName = dirPath + File.separator + configFileName; + + config = convert(fullFileName, className); + + } catch (Exception e) { + log.error("Failed to convert yaml file " + configFileName + + " to object.", e); + } + + return config; + } + + public <T> T convert(String fullFileName, Class<T> className) { + + T config = null; + + Yaml yaml = getYamlByClassName(className); + + InputStream in = null; + try { + + File f = new File(fullFileName); + if (false == f.exists()) { + log.warn("The file " + fullFileName + + " cannot be found. Ignore reading configuration."); + return null; + } + in = Files.newInputStream(Paths.get(fullFileName)); + + config = yaml.loadAs(in, className); + + // System.out.println(config.toString()); + } catch (Exception e) { + log.error("Failed to convert yaml file " + fullFileName + + " to object.", e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + return config; + } + + public <T> T convertFromString(String yamlContents, Class<T> className) { + + T config = null; + Yaml yaml = new Yaml(); + try { + Object data = yaml.load(yamlContents); + // convert it manually with jackson instead of using snakeyaml auto converter, + // because of problematic complex objects like JtoscaValidationIssueConfiguration + ObjectMapper mapper = new ObjectMapper(); + config = mapper.convertValue(data, className); + } catch (Exception e){ + log.error("Failed to convert YAML {} to object." , yamlContents, e); + } + + return config; + } +} |