diff options
author | vasraz <vasyl.razinkov@est.tech> | 2021-03-22 15:33:06 +0000 |
---|---|---|
committer | Christophe Closset <christophe.closset@intl.att.com> | 2021-03-24 06:59:47 +0000 |
commit | d378c37fbd1ecec7b43394926f1ca32a695e07de (patch) | |
tree | 5c8a085f8732f980d871d966ac49361644efa698 /openecomp-be/lib/openecomp-sdc-translator-lib | |
parent | a6ae7294ecd336d7e88f915710b08e2658eaee00 (diff) |
Reformat openecomp-be
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech>
Issue-ID: SDC-3449
Change-Id: I13e02322f8e00820cc5a1d85752caaeda9bf10d1
Diffstat (limited to 'openecomp-be/lib/openecomp-sdc-translator-lib')
123 files changed, 7906 insertions, 11244 deletions
diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/api/HeatToToscaTranslator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/api/HeatToToscaTranslator.java index f00017a229..614ea6ffdc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/api/HeatToToscaTranslator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/api/HeatToToscaTranslator.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,36 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.translator.api; - -import org.openecomp.core.translator.datatypes.TranslatorOutput; -import org.openecomp.sdc.datatypes.error.ErrorMessage; - import java.io.InputStream; import java.util.List; import java.util.Map; - - - +import org.openecomp.core.translator.datatypes.TranslatorOutput; +import org.openecomp.sdc.datatypes.error.ErrorMessage; public interface HeatToToscaTranslator { - void addManifest(String name, byte[] content); - - void addFile(String name, byte[] content); + void addManifest(String name, byte[] content); - void addFile(String name, InputStream content); + void addFile(String name, byte[] content); - // return Map, key - file name which has error - // value - the error code - Map<String, List<ErrorMessage>> validate(); + void addFile(String name, InputStream content); + // return Map, key - file name which has error - TranslatorOutput translate(); + // value - the error code + Map<String, List<ErrorMessage>> validate(); - void addExternalArtifacts(String name, byte[] content); + TranslatorOutput translate(); - void addExternalArtifacts(String name, InputStream content); + void addExternalArtifacts(String name, byte[] content); + void addExternalArtifacts(String name, InputStream content); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/datatypes/TranslatorOutput.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/datatypes/TranslatorOutput.java index c9169446ef..bceb963f50 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/datatypes/TranslatorOutput.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/datatypes/TranslatorOutput.java @@ -13,21 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.translator.datatypes; +import java.util.List; +import java.util.Map; import lombok.Data; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import java.util.List; -import java.util.Map; - - @Data public class TranslatorOutput { - private Map<String, List<ErrorMessage>> errorMessages; - private ToscaServiceModel toscaServiceModel; - private ToscaServiceModel nonUnifiedToscaServiceModel; + private Map<String, List<ErrorMessage>> errorMessages; + private ToscaServiceModel toscaServiceModel; + private ToscaServiceModel nonUnifiedToscaServiceModel; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/factory/HeatToToscaTranslatorFactory.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/factory/HeatToToscaTranslatorFactory.java index ebc497374d..6d3e9f80c5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/factory/HeatToToscaTranslatorFactory.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/factory/HeatToToscaTranslatorFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.translator.factory; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.translator.api.HeatToToscaTranslator; +public abstract class HeatToToscaTranslatorFactory extends AbstractComponentFactory<HeatToToscaTranslator> { - -public abstract class HeatToToscaTranslatorFactory - extends AbstractComponentFactory<HeatToToscaTranslator> { - - public static HeatToToscaTranslatorFactory getInstance() { - return getInstance(HeatToToscaTranslatorFactory.class); - } + public static HeatToToscaTranslatorFactory getInstance() { + return getInstance(HeatToToscaTranslatorFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java index 38bfc99c54..1ca3579c85 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,41 +17,41 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca; public class AttachedPropertyVal { - private Object propertyValue; - private ReferenceType referenceType; - - /** - * Instantiates a new Attached resource id. - * - * @param propertyValue the property value - * @param referenceType the reference type - */ - public AttachedPropertyVal(Object propertyValue, ReferenceType referenceType) { - this.referenceType = referenceType; - this.propertyValue = propertyValue; - } - - public Object getPropertyValue() { - return propertyValue; - } - - public ReferenceType getReferenceType() { - return referenceType; - } - - public boolean isGetResource() { - return referenceType == ReferenceType.GET_RESOURCE; - } - - public boolean isGetParam() { - return referenceType == ReferenceType.GET_PARAM; - } - - public boolean isGetAttr() { - return referenceType == ReferenceType.GET_ATTR; - } + + private Object propertyValue; + private ReferenceType referenceType; + + /** + * Instantiates a new Attached resource id. + * + * @param propertyValue the property value + * @param referenceType the reference type + */ + public AttachedPropertyVal(Object propertyValue, ReferenceType referenceType) { + this.referenceType = referenceType; + this.propertyValue = propertyValue; + } + + public Object getPropertyValue() { + return propertyValue; + } + + public ReferenceType getReferenceType() { + return referenceType; + } + + public boolean isGetResource() { + return referenceType == ReferenceType.GET_RESOURCE; + } + + public boolean isGetParam() { + return referenceType == ReferenceType.GET_PARAM; + } + + public boolean isGetAttr() { + return referenceType == ReferenceType.GET_ATTR; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java index 16baf4e84b..55a40dfc7e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,49 +17,48 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca; public class AttachedResourceId { - private Object translatedId; - private Object entityId; - private ReferenceType resourceReferenceType; - /** - * Instantiates a new Attached resource id. - * - * @param translatedId the translated id - * @param entityId the entity id - * @param resourceReferenceType the resource reference type - */ - public AttachedResourceId(Object translatedId, Object entityId, - ReferenceType resourceReferenceType) { - this.translatedId = translatedId; - this.resourceReferenceType = resourceReferenceType; - this.entityId = entityId; - } + private Object translatedId; + private Object entityId; + private ReferenceType resourceReferenceType; + + /** + * Instantiates a new Attached resource id. + * + * @param translatedId the translated id + * @param entityId the entity id + * @param resourceReferenceType the resource reference type + */ + public AttachedResourceId(Object translatedId, Object entityId, ReferenceType resourceReferenceType) { + this.translatedId = translatedId; + this.resourceReferenceType = resourceReferenceType; + this.entityId = entityId; + } - public Object getEntityId() { - return entityId; - } + public Object getEntityId() { + return entityId; + } - public Object getTranslatedId() { - return translatedId; - } + public Object getTranslatedId() { + return translatedId; + } - public ReferenceType getResourceReferenceType() { - return resourceReferenceType; - } + public ReferenceType getResourceReferenceType() { + return resourceReferenceType; + } - public boolean isGetResource() { - return resourceReferenceType == ReferenceType.GET_RESOURCE; - } + public boolean isGetResource() { + return resourceReferenceType == ReferenceType.GET_RESOURCE; + } - public boolean isGetParam() { - return resourceReferenceType == ReferenceType.GET_PARAM; - } + public boolean isGetParam() { + return resourceReferenceType == ReferenceType.GET_PARAM; + } - public boolean isGetAttr() { - return resourceReferenceType == ReferenceType.GET_ATTR; - } + public boolean isGetAttr() { + return resourceReferenceType == ReferenceType.GET_ATTR; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java index 06d96bc3c1..fd0d733a65 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,67 +17,63 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca; -import org.apache.commons.collections.CollectionUtils; - import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; +import org.apache.commons.collections.CollectionUtils; public class PropertyRegexMatcher { - private String propertyName; - private List<Pattern> regexPatterns; - private String stringToSearchForPropertyValue; - - /** - * Constractor for creating PropertyRegexMatcher. - * @param propertyName property name - * @param regexPatterns regex pattern - * @param stringToSearchForPropertyValue string for search in the property value manipulation - */ - public PropertyRegexMatcher(String propertyName, - List<String> regexPatterns, - String stringToSearchForPropertyValue) { - this.propertyName = propertyName; - setRegex(regexPatterns); - this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; - } - public String getPropertyName() { - return propertyName; - } + private String propertyName; + private List<Pattern> regexPatterns; + private String stringToSearchForPropertyValue; - public void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } + /** + * Constractor for creating PropertyRegexMatcher. + * + * @param propertyName property name + * @param regexPatterns regex pattern + * @param stringToSearchForPropertyValue string for search in the property value manipulation + */ + public PropertyRegexMatcher(String propertyName, List<String> regexPatterns, String stringToSearchForPropertyValue) { + this.propertyName = propertyName; + setRegex(regexPatterns); + this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; + } - /** - * Sets regex. - * - * @param regexPatterns the regex patterns - */ - public void setRegex(List<String> regexPatterns) { - if (CollectionUtils.isEmpty(this.regexPatterns)) { - this.regexPatterns = new ArrayList<>(); + public String getPropertyName() { + return propertyName; } - for (String regexPattern : regexPatterns) { - this.regexPatterns.add(Pattern.compile(regexPattern)); + public void setPropertyName(String propertyName) { + this.propertyName = propertyName; } - } - public List<Pattern> getRegexPatterns() { - return regexPatterns; - } + /** + * Sets regex. + * + * @param regexPatterns the regex patterns + */ + public void setRegex(List<String> regexPatterns) { + if (CollectionUtils.isEmpty(this.regexPatterns)) { + this.regexPatterns = new ArrayList<>(); + } + for (String regexPattern : regexPatterns) { + this.regexPatterns.add(Pattern.compile(regexPattern)); + } + } - public String getStringToSearchForPropertyValue() { - return stringToSearchForPropertyValue; - } + public List<Pattern> getRegexPatterns() { + return regexPatterns; + } - public void setStringToSearchForPropertyValue(String stringToSearchForPropertyValue) { - this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; - } + public String getStringToSearchForPropertyValue() { + return stringToSearchForPropertyValue; + } + public void setStringToSearchForPropertyValue(String stringToSearchForPropertyValue) { + this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java index 1f90db9cb3..b8ab508303 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca; -public enum ReferenceType { - GET_RESOURCE, GET_PARAM, GET_ATTR, OTHER -} +public enum ReferenceType {GET_RESOURCE, GET_PARAM, GET_ATTR, OTHER} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java index 76ef37327e..836b2fedef 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java @@ -13,17 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca; - - import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; +import java.io.InputStream; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import org.apache.commons.collections.MapUtils; - import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; +import org.onap.sdc.tosca.datatypes.model.NodeTemplate; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; @@ -32,8 +38,6 @@ import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestFile; import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.onap.sdc.tosca.datatypes.model.NodeTemplate; -import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionEntity; @@ -41,8 +45,8 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.compositi import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeConsolidationDataHandler; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationDataHandler; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortConsolidationDataHandler; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedConsolidationDataHandler; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortConsolidationDataHandler; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.SubInterfaceConsolidationDataHandler; import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType; @@ -51,619 +55,519 @@ import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.errors.DuplicateResourceIdsInDifferentFilesErrorBuilder; import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; -import java.io.InputStream; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - public class TranslationContext { - private ManifestFile manifest; - - - private static final Map<String, Map<String, Map<String, String>>> translationMapping; - private static final Map<String, ServiceTemplate> globalServiceTemplates; - private static final Map<String, ImplementationConfiguration> nameExtractorImplMap; - private static final List<String> vfcGroupSubInterfaceExposedProperties; - private static final List<String> enrichPortResourceProperties; - private static final ImplementationConfiguration vfcInstanceGroupConfiguration; - - private static Map<String, ImplementationConfiguration> supportedConsolidationComputeResources; - private static Map<String, ImplementationConfiguration> supportedConsolidationPortResources; - - private final FileContentHandler files = new FileContentHandler(); - private final Map<String, FileData.Type> manifestFiles = new HashMap<>(); - //Key - file name, value - file type - private final Set<String> nestedHeatsFiles = new HashSet<>(); - private final FileContentHandler externalArtifacts = new FileContentHandler(); - // Key - heat file name,value - set of heat resource ids which were translated - private final Map<String, Set<String>> translatedResources = new HashMap<>(); - // Key - heat file name, value - translated Node template id - private final Map<String, Set<String>> heatStackGroupMembers = new HashMap<>(); - // Key - heat file name, value - Map with Key - heat resource Id, Value - tosca entity template id - private final Map<String, Map<String, String>> translatedIds = new HashMap<>(); - // key - service template type, value - translated service templates - private final Map<String, ServiceTemplate> translatedServiceTemplates = new HashMap<>(); - //key - heat param name, value - shared resource data - private final Map<String, TranslatedHeatResource> heatSharedResourcesByParam = new HashMap<>(); - //key - translated substitute service template file name, value - source nested heat file name - private final Map<String, String> nestedHeatFileName = new HashMap<>(); - //Key - heat file name,value - Map eith key - heat pseudo param name, - // value - translated tosca parameter name - private final Map<String, Map<String, String>> usedHeatPseudoParams = new HashMap<>(); - //Consolidation data gathered for Unified TOSCA model - private ConsolidationData consolidationData = new ConsolidationData(); - private Map<String, UnifiedSubstitutionData> unifiedSubstitutionData = new HashMap<>(); - private final Set<String> unifiedHandledServiceTemplates = new HashSet<>(); - - private final Map<String, Map<String, Map<String, Integer>>> requirementIdAppearanceInNodeTemplate = new HashMap<>(); - - private final Set<String> serviceTemplatesWithoutNodeTemplateSection = new HashSet<>(); - - private final Set<String> nodeTemplateIdsPointingToStWithoutNodeTemplates = new HashSet<>(); - - //Key - service template name, value - Map of key: node template id, value: properties with %index% - private final Map<String, ListMultimap<String, String>> indexVarProperties = new HashMap<>(); - - static { - Configuration config = ConfigurationManager.lookup(); - translationMapping = - config.generateMap(ConfigConstants.MAPPING_NAMESPACE, ConfigConstants.RESOURCE_MAPPING_KEY); - try { - globalServiceTemplates = - GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP); - } catch (Exception exc) { - throw new RuntimeException("Failed to load GlobalTypes", exc); - } - nameExtractorImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, - ConfigConstants.NAMING_CONVENTION_EXTRACTOR_IMPL_KEY, ImplementationConfiguration.class); - supportedConsolidationComputeResources = config.populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, - ConfigConstants.SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY, ImplementationConfiguration.class); - supportedConsolidationPortResources = config.populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, - ConfigConstants.SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY, ImplementationConfiguration.class); - enrichPortResourceProperties = config.getAsStringValues(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, - ConfigConstants.ENRICH_PORT_RESOURCE_PROP); - vfcInstanceGroupConfiguration = getVfcInstanceGroupConfiguration(config); - vfcGroupSubInterfaceExposedProperties = config.getAsStringValues(ConfigConstants.UNIFIED_MODEL_NAMESPACE, - ConfigConstants.FULL_EXPOSED_PROPERTIES_KEY); - } - - - private static ImplementationConfiguration getVfcInstanceGroupConfiguration(Configuration config) { - Map<String, ImplementationConfiguration> supportedUnifiedModelProperties = - config.populateMap(ConfigConstants.UNIFIED_MODEL_NAMESPACE, ConfigConstants.UNIFIED_MODEL_IMPL_KEY, - ImplementationConfiguration.class); - return MapUtils.isEmpty(supportedUnifiedModelProperties) ? null : supportedUnifiedModelProperties.get(ConfigConstants.VFC_INSTANCE_GROUP_KEY); - } - - public static boolean isVfcInstanceGroupingEnabled() { - return Objects.nonNull(vfcInstanceGroupConfiguration) && vfcInstanceGroupConfiguration.isEnable(); - } - - public static List<String> getExposedVfcInstanceGroupingProperties() { - return vfcGroupSubInterfaceExposedProperties; - } - - public static List<String> getEnrichPortResourceProperties() { - return enrichPortResourceProperties; - } - - public static Map<String, ImplementationConfiguration> getSupportedConsolidationComputeResources() { - return supportedConsolidationComputeResources; - } - - public static void setSupportedConsolidationComputeResources(Map<String, ImplementationConfiguration> supportedConsolidationComputeResources) { - TranslationContext.supportedConsolidationComputeResources = supportedConsolidationComputeResources; - } - - public static Map<String, ImplementationConfiguration> getSupportedConsolidationPortResources() { - return supportedConsolidationPortResources; - } - - public static void setSupportedConsolidationPortResources(Map<String, ImplementationConfiguration> supportedConsolidationPortResources) { - TranslationContext.supportedConsolidationPortResources = supportedConsolidationPortResources; - } - - /** - * Get nameExtractor implemetation class instance. - * - * @param extractorImplKey configuration key for the implementation class - * @return implemetation class instance - */ - public static NameExtractor getNameExtractorImpl(String extractorImplKey) { - String nameExtractorImplClassName = nameExtractorImplMap.get(extractorImplKey).getImplementationClass(); - - return CommonMethods.newInstance(nameExtractorImplClassName, NameExtractor.class); - } - - public Map<String, UnifiedSubstitutionData> getUnifiedSubstitutionData() { - return unifiedSubstitutionData; - } - - public void setUnifiedSubstitutionData(Map<String, UnifiedSubstitutionData> unifiedSubstitutionData) { - this.unifiedSubstitutionData = unifiedSubstitutionData; - } - - public void addCleanedNodeTemplate(String serviceTemplateName, String nodeTemplateId, UnifiedCompositionEntity unifiedCompositionEntity, - NodeTemplate nodeTemplate) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName) - .addCleanedNodeTemplate(nodeTemplateId, unifiedCompositionEntity, nodeTemplate); - } - - public Optional<List<String>> getIndexVarProperties(String serviceTemplateName, String nodeTemplateId) { - ListMultimap<String, String> serviceTemplateIndexVarProperties = this.indexVarProperties.get(serviceTemplateName); - if (Objects.nonNull(serviceTemplateIndexVarProperties)) { - return Optional.of(this.indexVarProperties.get(serviceTemplateName).get(nodeTemplateId)); - } - return Optional.empty(); - } - - public void addIndexVarProperties(String serviceTemplateName, String nodeTemplateId, List<String> indexVarProperties) { - this.indexVarProperties.putIfAbsent(serviceTemplateName, ArrayListMultimap.create()); - this.indexVarProperties.get(serviceTemplateName).putAll(nodeTemplateId, indexVarProperties); - } - - public NodeTemplate getCleanedNodeTemplate(String serviceTemplateName, String nodeTemplateId) { - return this.unifiedSubstitutionData.get(serviceTemplateName).getCleanedNodeTemplate(nodeTemplateId); - } - - public void addUnifiedNestedNodeTemplateId(String serviceTemplateName, String nestedNodeTemplateId, String unifiedNestedNodeTemplateId) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName) - .addUnifiedNestedNodeTemplateId(nestedNodeTemplateId, unifiedNestedNodeTemplateId); - } - - public Optional<String> getUnifiedNestedNodeTemplateId(String serviceTemplateName, String nestedNodeTemplateId) { - return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty() : - this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTemplateId(nestedNodeTemplateId); - } - - public void addUnifiedNestedNodeTypeId(String serviceTemplateName, String nestedNodeTypeId, String unifiedNestedNodeTypeId) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName) - .addUnifiedNestedNodeTypeId(nestedNodeTypeId, unifiedNestedNodeTypeId); - } - - public Optional<String> getUnifiedNestedNodeTypeId(String serviceTemplateName, String nestedNodeTemplateId) { - UnifiedSubstitutionData substitutionData = this.unifiedSubstitutionData.get(serviceTemplateName); - return substitutionData == null ? Optional.empty() : - substitutionData.getUnifiedNestedNodeTypeId(nestedNodeTemplateId); - } - - public ConsolidationData getConsolidationData() { - return consolidationData; - } - - public void setConsolidationData(ConsolidationData consolidationData) { - this.consolidationData = consolidationData; - } - - public Optional<ConsolidationDataHandler> getConsolidationDataHandler(ConsolidationEntityType type) { - return consolidationData.getConsolidationDataHandler(type); - } - - public ComputeConsolidationDataHandler getComputeConsolidationDataHandler() { - return consolidationData.getComputeConsolidationDataHandler(); - } - - public PortConsolidationDataHandler getPortConsolidationDataHandler() { - return consolidationData.getPortConsolidationDataHandler(); - } - - public NestedConsolidationDataHandler getNestedConsolidationDataHandler() { - return consolidationData.getNestedConsolidationDataHandler(); - } - - public SubInterfaceConsolidationDataHandler getSubInterfaceConsolidationDataHandler() { - return consolidationData.getSubInterfaceConsolidationDataHandler(); - } - - public void addManifestFile(String fileName, FileData.Type fileType) { - this.manifestFiles.put(fileName, fileType); - } - - public Set<String> getNestedHeatsFiles() { - return nestedHeatsFiles; - } - - public Map<String, Set<String>> getHeatStackGroupMembers() { - return heatStackGroupMembers; - } - - public FileContentHandler getFiles() { - return files; - } - - public void setFiles(Map<String, byte[]> files) { - this.files.setFiles(files); - } - - public InputStream getFileContentAsStream(final String fileName) { - return files.getFileContentAsStream(fileName); - } - - public void addFile(String name, byte[] content) { - files.addFile(name, content); - } - - public ManifestFile getManifest() { - return manifest; - } - - public void setManifest(ManifestFile manifest) { - this.manifest = manifest; - } - - public Map<String, Set<String>> getTranslatedResources() { - return translatedResources; - } - - public Map<String, Map<String, String>> getTranslatedIds() { - return translatedIds; - } - - public Set<String> getAllTranslatedResourceIdsFromDiffNestedFiles(String - nestedHeatFileNameToSkip) { - Set<String> allTranslatedResourceIds = new HashSet<>(); - - this.translatedIds.entrySet().stream().filter( - heatFileNameToTranslatedIdsEntry -> !heatFileNameToTranslatedIdsEntry.getKey() - .equals(nestedHeatFileNameToSkip)).forEach(heatFileNameToTranslatedIdsEntry -> - allTranslatedResourceIds.addAll(heatFileNameToTranslatedIdsEntry.getValue().keySet()) - ); + private ManifestFile manifest; + private static final Map<String, Map<String, Map<String, String>>> translationMapping; + private static final Map<String, ServiceTemplate> globalServiceTemplates; + private static final Map<String, ImplementationConfiguration> nameExtractorImplMap; + private static final List<String> vfcGroupSubInterfaceExposedProperties; + private static final List<String> enrichPortResourceProperties; + private static final ImplementationConfiguration vfcInstanceGroupConfiguration; + private static Map<String, ImplementationConfiguration> supportedConsolidationComputeResources; + private static Map<String, ImplementationConfiguration> supportedConsolidationPortResources; + private final FileContentHandler files = new FileContentHandler(); + private final Map<String, FileData.Type> manifestFiles = new HashMap<>(); + //Key - file name, value - file type + private final Set<String> nestedHeatsFiles = new HashSet<>(); + private final FileContentHandler externalArtifacts = new FileContentHandler(); + // Key - heat file name,value - set of heat resource ids which were translated + private final Map<String, Set<String>> translatedResources = new HashMap<>(); + // Key - heat file name, value - translated Node template id + private final Map<String, Set<String>> heatStackGroupMembers = new HashMap<>(); + // Key - heat file name, value - Map with Key - heat resource Id, Value - tosca entity template id + private final Map<String, Map<String, String>> translatedIds = new HashMap<>(); + // key - service template type, value - translated service templates + private final Map<String, ServiceTemplate> translatedServiceTemplates = new HashMap<>(); + //key - heat param name, value - shared resource data + private final Map<String, TranslatedHeatResource> heatSharedResourcesByParam = new HashMap<>(); + //key - translated substitute service template file name, value - source nested heat file name + private final Map<String, String> nestedHeatFileName = new HashMap<>(); + //Key - heat file name,value - Map eith key - heat pseudo param name, + + // value - translated tosca parameter name + private final Map<String, Map<String, String>> usedHeatPseudoParams = new HashMap<>(); + //Consolidation data gathered for Unified TOSCA model + private ConsolidationData consolidationData = new ConsolidationData(); + private Map<String, UnifiedSubstitutionData> unifiedSubstitutionData = new HashMap<>(); + private final Set<String> unifiedHandledServiceTemplates = new HashSet<>(); + private final Map<String, Map<String, Map<String, Integer>>> requirementIdAppearanceInNodeTemplate = new HashMap<>(); + private final Set<String> serviceTemplatesWithoutNodeTemplateSection = new HashSet<>(); + private final Set<String> nodeTemplateIdsPointingToStWithoutNodeTemplates = new HashSet<>(); + //Key - service template name, value - Map of key: node template id, value: properties with %index% + private final Map<String, ListMultimap<String, String>> indexVarProperties = new HashMap<>(); + + static { + Configuration config = ConfigurationManager.lookup(); + translationMapping = config.generateMap(ConfigConstants.MAPPING_NAMESPACE, ConfigConstants.RESOURCE_MAPPING_KEY); + try { + globalServiceTemplates = GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP); + } catch (Exception exc) { + throw new RuntimeException("Failed to load GlobalTypes", exc); + } + nameExtractorImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, ConfigConstants.NAMING_CONVENTION_EXTRACTOR_IMPL_KEY, + ImplementationConfiguration.class); + supportedConsolidationComputeResources = config + .populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants.SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY, + ImplementationConfiguration.class); + supportedConsolidationPortResources = config + .populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants.SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY, + ImplementationConfiguration.class); + enrichPortResourceProperties = config + .getAsStringValues(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants.ENRICH_PORT_RESOURCE_PROP); + vfcInstanceGroupConfiguration = getVfcInstanceGroupConfiguration(config); + vfcGroupSubInterfaceExposedProperties = config + .getAsStringValues(ConfigConstants.UNIFIED_MODEL_NAMESPACE, ConfigConstants.FULL_EXPOSED_PROPERTIES_KEY); + } + + private static ImplementationConfiguration getVfcInstanceGroupConfiguration(Configuration config) { + Map<String, ImplementationConfiguration> supportedUnifiedModelProperties = config + .populateMap(ConfigConstants.UNIFIED_MODEL_NAMESPACE, ConfigConstants.UNIFIED_MODEL_IMPL_KEY, ImplementationConfiguration.class); + return MapUtils.isEmpty(supportedUnifiedModelProperties) ? null : supportedUnifiedModelProperties.get(ConfigConstants.VFC_INSTANCE_GROUP_KEY); + } + + public static boolean isVfcInstanceGroupingEnabled() { + return Objects.nonNull(vfcInstanceGroupConfiguration) && vfcInstanceGroupConfiguration.isEnable(); + } + + public static List<String> getExposedVfcInstanceGroupingProperties() { + return vfcGroupSubInterfaceExposedProperties; + } + + public static List<String> getEnrichPortResourceProperties() { + return enrichPortResourceProperties; + } + + public static Map<String, ImplementationConfiguration> getSupportedConsolidationComputeResources() { + return supportedConsolidationComputeResources; + } + + public static void setSupportedConsolidationComputeResources(Map<String, ImplementationConfiguration> supportedConsolidationComputeResources) { + TranslationContext.supportedConsolidationComputeResources = supportedConsolidationComputeResources; + } + + public static Map<String, ImplementationConfiguration> getSupportedConsolidationPortResources() { + return supportedConsolidationPortResources; + } + + public static void setSupportedConsolidationPortResources(Map<String, ImplementationConfiguration> supportedConsolidationPortResources) { + TranslationContext.supportedConsolidationPortResources = supportedConsolidationPortResources; + } + + /** + * Get nameExtractor implemetation class instance. + * + * @param extractorImplKey configuration key for the implementation class + * @return implemetation class instance + */ + public static NameExtractor getNameExtractorImpl(String extractorImplKey) { + String nameExtractorImplClassName = nameExtractorImplMap.get(extractorImplKey).getImplementationClass(); + return CommonMethods.newInstance(nameExtractorImplClassName, NameExtractor.class); + } + + public Map<String, UnifiedSubstitutionData> getUnifiedSubstitutionData() { + return unifiedSubstitutionData; + } + + public void setUnifiedSubstitutionData(Map<String, UnifiedSubstitutionData> unifiedSubstitutionData) { + this.unifiedSubstitutionData = unifiedSubstitutionData; + } + + public void addCleanedNodeTemplate(String serviceTemplateName, String nodeTemplateId, UnifiedCompositionEntity unifiedCompositionEntity, + NodeTemplate nodeTemplate) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addCleanedNodeTemplate(nodeTemplateId, unifiedCompositionEntity, nodeTemplate); + } + + public Optional<List<String>> getIndexVarProperties(String serviceTemplateName, String nodeTemplateId) { + ListMultimap<String, String> serviceTemplateIndexVarProperties = this.indexVarProperties.get(serviceTemplateName); + if (Objects.nonNull(serviceTemplateIndexVarProperties)) { + return Optional.of(this.indexVarProperties.get(serviceTemplateName).get(nodeTemplateId)); + } + return Optional.empty(); + } + + public void addIndexVarProperties(String serviceTemplateName, String nodeTemplateId, List<String> indexVarProperties) { + this.indexVarProperties.putIfAbsent(serviceTemplateName, ArrayListMultimap.create()); + this.indexVarProperties.get(serviceTemplateName).putAll(nodeTemplateId, indexVarProperties); + } + + public NodeTemplate getCleanedNodeTemplate(String serviceTemplateName, String nodeTemplateId) { + return this.unifiedSubstitutionData.get(serviceTemplateName).getCleanedNodeTemplate(nodeTemplateId); + } + + public void addUnifiedNestedNodeTemplateId(String serviceTemplateName, String nestedNodeTemplateId, String unifiedNestedNodeTemplateId) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addUnifiedNestedNodeTemplateId(nestedNodeTemplateId, unifiedNestedNodeTemplateId); + } + + public Optional<String> getUnifiedNestedNodeTemplateId(String serviceTemplateName, String nestedNodeTemplateId) { + return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty() + : this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTemplateId(nestedNodeTemplateId); + } + + public void addUnifiedNestedNodeTypeId(String serviceTemplateName, String nestedNodeTypeId, String unifiedNestedNodeTypeId) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addUnifiedNestedNodeTypeId(nestedNodeTypeId, unifiedNestedNodeTypeId); + } - return allTranslatedResourceIds; - } + public Optional<String> getUnifiedNestedNodeTypeId(String serviceTemplateName, String nestedNodeTemplateId) { + UnifiedSubstitutionData substitutionData = this.unifiedSubstitutionData.get(serviceTemplateName); + return substitutionData == null ? Optional.empty() : substitutionData.getUnifiedNestedNodeTypeId(nestedNodeTemplateId); + } - // get tosca name from mapping configuration file - //element type - parameter/attribute - // element name - heat parameter/attribute name - //return value - tosca parameter/attribute name - public String getElementMapping(String resourceType, String elementType, String elementName) { - if (Objects.isNull(translationMapping.get(resourceType))) { - return null; - } - if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { - return null; - } - return translationMapping.get(resourceType).get(elementType).get(elementName); - } - - public Map<String, String> getElementMapping(String resourceType, String elementType) { - if (Objects.isNull(translationMapping.get(resourceType))) { - return null; - } - return translationMapping.get(resourceType).get(elementType); - } + public ConsolidationData getConsolidationData() { + return consolidationData; + } - public Set<String> getElementSet(String resourceType, String elementType) { - if (Objects.isNull(translationMapping.get(resourceType))) { - return new HashSet<>(); + public void setConsolidationData(ConsolidationData consolidationData) { + this.consolidationData = consolidationData; } - if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { - return new HashSet<>(); + + public Optional<ConsolidationDataHandler> getConsolidationDataHandler(ConsolidationEntityType type) { + return consolidationData.getConsolidationDataHandler(type); } - return translationMapping.get(resourceType).get(elementType).keySet(); - } - public Map<String, ServiceTemplate> getTranslatedServiceTemplates() { - return translatedServiceTemplates; - } - - public ServiceTemplate getGlobalSubstitutionServiceTemplate() { - return getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - } - - public FileContentHandler getExternalArtifacts() { - return externalArtifacts; - } - - public void addExternalArtifacts(String name, byte[] content) { - this.externalArtifacts.addFile(name, content); - } - - public Map<String, TranslatedHeatResource> getHeatSharedResourcesByParam() { - return heatSharedResourcesByParam; - } - - public void addHeatSharedResourcesByParam(String parameterName, String resourceId, - Resource resource) { - this.addHeatSharedResourcesByParam(parameterName, - new TranslatedHeatResource(resourceId, resource)); - } - - private void addHeatSharedResourcesByParam(String parameterName, - TranslatedHeatResource translatedHeatResource) { - this.heatSharedResourcesByParam.put(parameterName, translatedHeatResource); - } - - public Map<String, ServiceTemplate> getGlobalServiceTemplates() { - return globalServiceTemplates; - } - - public Map<String, String> getNestedHeatFileName() { - return nestedHeatFileName; - } - - public void addNestedHeatFileName(String substituteServiceTempalteName, - String nestedHeatFileName) { - this.nestedHeatFileName.put(substituteServiceTempalteName, nestedHeatFileName); - } - - public Map<String, Map<String, String>> getUsedHeatPseudoParams() { - return usedHeatPseudoParams; - } - - public void addUsedHeatPseudoParams(String heatFileName, String heatPseudoParam, String - translatedToscaParam) { - if (Objects.isNull(this.usedHeatPseudoParams.get(heatFileName))) { - this.usedHeatPseudoParams.put(heatFileName, new HashMap<>()); - } - this.usedHeatPseudoParams.get(heatFileName).put(heatPseudoParam, translatedToscaParam); - } - - public Set<String> getTranslatedResourceIdsFromOtherFiles(String fileNameToIgnore){ - if(MapUtils.isEmpty(this.translatedResources)){ - return new HashSet<>(); - } - - Set<String> translatedResourceIds = new HashSet<>(); - - this.translatedResources.entrySet().stream().filter(entry -> !entry.getKey().equals(fileNameToIgnore)) - .forEach(entry -> translatedResourceIds.addAll(entry.getValue())); - - return translatedResourceIds; - } - - /** - * Add the unified substitution data info in context. Contains a mapping of original node - * template id and the new node template id in the abstract substitute - * - * @param serviceTemplateFileName the service template file name - * @param originalNodeTemplateId the original node template id - * @param abstractNodeTemplateId the node template id in the abstract substitute - */ - public void addUnifiedSubstitutionData(String serviceTemplateFileName, - String originalNodeTemplateId, - String abstractNodeTemplateId) { - - Map<String, String> nodeAbstractNodeTemplateIdMap = this.getUnifiedSubstitutionData() - .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()) - .getNodesRelatedAbstractNode(); - - if (nodeAbstractNodeTemplateIdMap == null) { - nodeAbstractNodeTemplateIdMap = new HashMap<>(); - } - - if(nodeAbstractNodeTemplateIdMap.containsKey(originalNodeTemplateId)){ - throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(originalNodeTemplateId).build()); - } - nodeAbstractNodeTemplateIdMap.put(originalNodeTemplateId, abstractNodeTemplateId); - this.getUnifiedSubstitutionData().get(serviceTemplateFileName).setNodesRelatedAbstractNode( - nodeAbstractNodeTemplateIdMap); - } - - /** - * Add the unified substitution data info in context. Contains a mapping of original node - * template id and the new node template id in the abstract substitute - * - * @param serviceTemplateFileName the service template file name - * @param originalNodeTemplateId the original node template id - * @param substitutionServiceTemplateNodeTemplateId the node template id in the substitution - * service template - */ - public void addSubstitutionServiceTemplateUnifiedSubstitutionData( - String serviceTemplateFileName, - String originalNodeTemplateId, - String substitutionServiceTemplateNodeTemplateId) { - - Map<String, String> nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = this - .getUnifiedSubstitutionData() - .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()) - .getNodesRelatedSubstitutionServiceTemplateNode(); - - if (nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap == null) { - nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = new HashMap<>(); - } - nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap.put(originalNodeTemplateId, - substitutionServiceTemplateNodeTemplateId); - this.getUnifiedSubstitutionData().get(serviceTemplateFileName) - .setNodesRelatedSubstitutionServiceTemplateNode( - nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap); - } - - /** - * Get unified abstract node template which is mapped to the input node template id. - * - * @param serviceTemplate the service template - * @param nodeTemplateId the node template id - */ - public String getUnifiedAbstractNodeTemplateId(ServiceTemplate serviceTemplate, - String nodeTemplateId) { - UnifiedSubstitutionData unifiedSubsData = - this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); - return unifiedSubsData.getNodesRelatedAbstractNode().get(nodeTemplateId); - } - - /** - * Get unified node template in the substitution service template which is mapped to the - * original input node template id. - * - * @param serviceTemplate the service template - * @param nodeTemplateId the node template id - */ - public String getUnifiedSubstitutionNodeTemplateId(ServiceTemplate serviceTemplate, - String nodeTemplateId) { - UnifiedSubstitutionData unifiedSubsData = - this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); - return unifiedSubsData.getNodesRelatedSubstitutionServiceTemplateNode() - .get(nodeTemplateId); - } - - public int getHandledNestedComputeNodeTemplateIndex(String serviceTemplateName, - String computeType) { - return this.unifiedSubstitutionData.get(serviceTemplateName) - .getHandledNestedComputeNodeTemplateIndex(computeType); - } - - public void updateHandledComputeType(String serviceTemplateName, - String handledComputeType, - String nestedServiceTemplateFileName) { - String globalSTName = - ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - this.unifiedSubstitutionData.putIfAbsent( - globalSTName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(globalSTName) - .addHandledComputeType(handledComputeType); - this.unifiedSubstitutionData.get(globalSTName).addHandlesNestedServiceTemplate(nestedServiceTemplateFileName); - - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName).addHandlesNestedServiceTemplate(nestedServiceTemplateFileName); - } - - public void addHandledComputeTypeInServiceTemplate(String serviceTemplateName, - String handledComputeType){ - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName).addHandledComputeType(handledComputeType); - } - - public boolean isComputeTypeHandledInServiceTemplate(String serviceTemplateName, - String computeType) { - return !Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName)) - && this.unifiedSubstitutionData.get(serviceTemplateName) - .isComputeTypeHandledInServiceTemplate(computeType); - } - - public boolean isNestedServiceTemplateWasHandled(String serviceTemplateName, - String nestedServiceTemplateFileName) { - if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { - return false; - } - return this.unifiedSubstitutionData.get(serviceTemplateName) - .isNestedServiceTemplateWasHandled(nestedServiceTemplateFileName); - } - - public Set<String> getAllRelatedNestedNodeTypeIds() { - String globalName = "GlobalSubstitutionTypes"; - if (Objects.isNull(this.unifiedSubstitutionData) - || Objects.isNull(this.unifiedSubstitutionData.get(globalName))) { - return new HashSet<>(); - } - - return this.unifiedSubstitutionData.get(globalName).getAllRelatedNestedNodeTypeIds(); - } - - public boolean isUnifiedHandledServiceTemplate(ServiceTemplate serviceTemplate) { - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - return unifiedHandledServiceTemplates.contains(serviceTemplateFileName); - } - - - - public void addUnifiedHandledServiceTeamplte(ServiceTemplate serviceTemplate) { - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - this.unifiedHandledServiceTemplates.add(serviceTemplateFileName); - } - - public boolean isNestedNodeWasHandled(String serviceTemplateName, - String nestedNodeTemplateId) { - if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { - return false; - } - return this.unifiedSubstitutionData.get(serviceTemplateName) - .isNestedNodeWasHandled(nestedNodeTemplateId); - } - - public void addNestedNodeAsHandled(String serviceTemplateName, - String nestedNodeTemplateId) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName) - .addHandledNestedNodes(nestedNodeTemplateId); - } - - public void updateUsedTimesForNestedComputeNodeType(String serviceTemplateName, - String computeType) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - - this.unifiedSubstitutionData.get(serviceTemplateName) - .updateUsedTimesForNestedComputeNodeType(computeType); - } - - public int getGlobalNodeTypeIndex(String serviceTemplateName, - String computeType) { - if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { - return 0; - } - return this.unifiedSubstitutionData.get(serviceTemplateName).getGlobalNodeTypeIndex - (computeType); - } - - public void addNewPropertyIdToNodeTemplate(String serviceTemplateName, - String newPropertyId, - Object origPropertyValue){ - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName).addNewPropertyIdToNodeTemplate( - newPropertyId, origPropertyValue); - } - - public Optional<Object> getNewPropertyInputParamId(String serviceTemplateName, - String newPropertyId){ - if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){ - return Optional.empty(); - } - - return this.unifiedSubstitutionData.get(serviceTemplateName).getNewPropertyInputParam - (newPropertyId); - } + public ComputeConsolidationDataHandler getComputeConsolidationDataHandler() { + return consolidationData.getComputeConsolidationDataHandler(); + } - public Map<String, Object> getAllNewPropertyInputParamIdsPerNodeTenplateId(String serviceTemplateName){ - if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){ - return new HashMap<>(); + public PortConsolidationDataHandler getPortConsolidationDataHandler() { + return consolidationData.getPortConsolidationDataHandler(); } - return this.unifiedSubstitutionData.get(serviceTemplateName).getAllNewPropertyInputParamIds(); + public NestedConsolidationDataHandler getNestedConsolidationDataHandler() { + return consolidationData.getNestedConsolidationDataHandler(); + } - } + public SubInterfaceConsolidationDataHandler getSubInterfaceConsolidationDataHandler() { + return consolidationData.getSubInterfaceConsolidationDataHandler(); + } - public boolean isServiceTemplateWithoutNodeTemplatesSection(String serviceTemplateName){ - return Objects.nonNull(serviceTemplateName) - && serviceTemplatesWithoutNodeTemplateSection.contains(serviceTemplateName); - } + public void addManifestFile(String fileName, FileData.Type fileType) { + this.manifestFiles.put(fileName, fileType); + } - public void addServiceTemplateWithoutNodeTemplates(String serviceTemplateName){ - this.serviceTemplatesWithoutNodeTemplateSection.add(serviceTemplateName); - } + public Set<String> getNestedHeatsFiles() { + return nestedHeatsFiles; + } - public void addNestedNodeTemplateIdPointsToStWithoutNodeTemplates(String nodeTemplateId){ - this.nodeTemplateIdsPointingToStWithoutNodeTemplates.add(nodeTemplateId); - } + public Map<String, Set<String>> getHeatStackGroupMembers() { + return heatStackGroupMembers; + } - public boolean isNodeTemplateIdPointsToStWithoutNodeTemplates(String nodeTemplateId){ - return Objects.nonNull(nodeTemplateId) - && nodeTemplateIdsPointingToStWithoutNodeTemplates.contains(nodeTemplateId); - } + public FileContentHandler getFiles() { + return files; + } - public void updateRequirementAssignmentIdIndex(String serviceTemplateName, - String nodeTemplateId, - String requirementId){ - requirementIdAppearanceInNodeTemplate.putIfAbsent(serviceTemplateName, new HashMap<>()); - requirementIdAppearanceInNodeTemplate - .get(serviceTemplateName).putIfAbsent(nodeTemplateId, new HashMap<>()); + public void setFiles(Map<String, byte[]> files) { + this.files.setFiles(files); + } + + public InputStream getFileContentAsStream(final String fileName) { + return files.getFileContentAsStream(fileName); + } + + public void addFile(String name, byte[] content) { + files.addFile(name, content); + } - Map<String, Integer> requirementIdToAppearance = - requirementIdAppearanceInNodeTemplate.get(serviceTemplateName).get(nodeTemplateId); + public ManifestFile getManifest() { + return manifest; + } + + public void setManifest(ManifestFile manifest) { + this.manifest = manifest; + } + + public Map<String, Set<String>> getTranslatedResources() { + return translatedResources; + } - if(requirementIdToAppearance.containsKey(requirementId)){ - requirementIdToAppearance - .put(requirementId, requirementIdToAppearance.get(requirementId) + 1); - } else { - requirementIdToAppearance.put(requirementId, 0); + public Map<String, Map<String, String>> getTranslatedIds() { + return translatedIds; } - } + public Set<String> getAllTranslatedResourceIdsFromDiffNestedFiles(String nestedHeatFileNameToSkip) { + Set<String> allTranslatedResourceIds = new HashSet<>(); + this.translatedIds.entrySet().stream() + .filter(heatFileNameToTranslatedIdsEntry -> !heatFileNameToTranslatedIdsEntry.getKey().equals(nestedHeatFileNameToSkip)) + .forEach(heatFileNameToTranslatedIdsEntry -> allTranslatedResourceIds.addAll(heatFileNameToTranslatedIdsEntry.getValue().keySet())); + return allTranslatedResourceIds; + } + // get tosca name from mapping configuration file + + //element type - parameter/attribute + + // element name - heat parameter/attribute name + + //return value - tosca parameter/attribute name + public String getElementMapping(String resourceType, String elementType, String elementName) { + if (Objects.isNull(translationMapping.get(resourceType))) { + return null; + } + if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { + return null; + } + return translationMapping.get(resourceType).get(elementType).get(elementName); + } + + public Map<String, String> getElementMapping(String resourceType, String elementType) { + if (Objects.isNull(translationMapping.get(resourceType))) { + return null; + } + return translationMapping.get(resourceType).get(elementType); + } + + public Set<String> getElementSet(String resourceType, String elementType) { + if (Objects.isNull(translationMapping.get(resourceType))) { + return new HashSet<>(); + } + if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { + return new HashSet<>(); + } + return translationMapping.get(resourceType).get(elementType).keySet(); + } + + public Map<String, ServiceTemplate> getTranslatedServiceTemplates() { + return translatedServiceTemplates; + } + + public ServiceTemplate getGlobalSubstitutionServiceTemplate() { + return getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + } + + public FileContentHandler getExternalArtifacts() { + return externalArtifacts; + } + + public void addExternalArtifacts(String name, byte[] content) { + this.externalArtifacts.addFile(name, content); + } + + public Map<String, TranslatedHeatResource> getHeatSharedResourcesByParam() { + return heatSharedResourcesByParam; + } + + public void addHeatSharedResourcesByParam(String parameterName, String resourceId, Resource resource) { + this.addHeatSharedResourcesByParam(parameterName, new TranslatedHeatResource(resourceId, resource)); + } + + private void addHeatSharedResourcesByParam(String parameterName, TranslatedHeatResource translatedHeatResource) { + this.heatSharedResourcesByParam.put(parameterName, translatedHeatResource); + } + + public Map<String, ServiceTemplate> getGlobalServiceTemplates() { + return globalServiceTemplates; + } + + public Map<String, String> getNestedHeatFileName() { + return nestedHeatFileName; + } + + public void addNestedHeatFileName(String substituteServiceTempalteName, String nestedHeatFileName) { + this.nestedHeatFileName.put(substituteServiceTempalteName, nestedHeatFileName); + } + + public Map<String, Map<String, String>> getUsedHeatPseudoParams() { + return usedHeatPseudoParams; + } + + public void addUsedHeatPseudoParams(String heatFileName, String heatPseudoParam, String translatedToscaParam) { + if (Objects.isNull(this.usedHeatPseudoParams.get(heatFileName))) { + this.usedHeatPseudoParams.put(heatFileName, new HashMap<>()); + } + this.usedHeatPseudoParams.get(heatFileName).put(heatPseudoParam, translatedToscaParam); + } + + public Set<String> getTranslatedResourceIdsFromOtherFiles(String fileNameToIgnore) { + if (MapUtils.isEmpty(this.translatedResources)) { + return new HashSet<>(); + } + Set<String> translatedResourceIds = new HashSet<>(); + this.translatedResources.entrySet().stream().filter(entry -> !entry.getKey().equals(fileNameToIgnore)) + .forEach(entry -> translatedResourceIds.addAll(entry.getValue())); + return translatedResourceIds; + } + + /** + * Add the unified substitution data info in context. Contains a mapping of original node template id and the new node template id in the abstract + * substitute + * + * @param serviceTemplateFileName the service template file name + * @param originalNodeTemplateId the original node template id + * @param abstractNodeTemplateId the node template id in the abstract substitute + */ + public void addUnifiedSubstitutionData(String serviceTemplateFileName, String originalNodeTemplateId, String abstractNodeTemplateId) { + Map<String, String> nodeAbstractNodeTemplateIdMap = this.getUnifiedSubstitutionData() + .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()).getNodesRelatedAbstractNode(); + if (nodeAbstractNodeTemplateIdMap == null) { + nodeAbstractNodeTemplateIdMap = new HashMap<>(); + } + if (nodeAbstractNodeTemplateIdMap.containsKey(originalNodeTemplateId)) { + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(originalNodeTemplateId).build()); + } + nodeAbstractNodeTemplateIdMap.put(originalNodeTemplateId, abstractNodeTemplateId); + this.getUnifiedSubstitutionData().get(serviceTemplateFileName).setNodesRelatedAbstractNode(nodeAbstractNodeTemplateIdMap); + } + + /** + * Add the unified substitution data info in context. Contains a mapping of original node template id and the new node template id in the abstract + * substitute + * + * @param serviceTemplateFileName the service template file name + * @param originalNodeTemplateId the original node template id + * @param substitutionServiceTemplateNodeTemplateId the node template id in the substitution service template + */ + public void addSubstitutionServiceTemplateUnifiedSubstitutionData(String serviceTemplateFileName, String originalNodeTemplateId, + String substitutionServiceTemplateNodeTemplateId) { + Map<String, String> nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = this.getUnifiedSubstitutionData() + .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()).getNodesRelatedSubstitutionServiceTemplateNode(); + if (nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap == null) { + nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = new HashMap<>(); + } + nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap.put(originalNodeTemplateId, substitutionServiceTemplateNodeTemplateId); + this.getUnifiedSubstitutionData().get(serviceTemplateFileName) + .setNodesRelatedSubstitutionServiceTemplateNode(nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap); + } + + /** + * Get unified abstract node template which is mapped to the input node template id. + * + * @param serviceTemplate the service template + * @param nodeTemplateId the node template id + */ + public String getUnifiedAbstractNodeTemplateId(ServiceTemplate serviceTemplate, String nodeTemplateId) { + UnifiedSubstitutionData unifiedSubsData = this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + return unifiedSubsData.getNodesRelatedAbstractNode().get(nodeTemplateId); + } + + /** + * Get unified node template in the substitution service template which is mapped to the original input node template id. + * + * @param serviceTemplate the service template + * @param nodeTemplateId the node template id + */ + public String getUnifiedSubstitutionNodeTemplateId(ServiceTemplate serviceTemplate, String nodeTemplateId) { + UnifiedSubstitutionData unifiedSubsData = this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + return unifiedSubsData.getNodesRelatedSubstitutionServiceTemplateNode().get(nodeTemplateId); + } + + public int getHandledNestedComputeNodeTemplateIndex(String serviceTemplateName, String computeType) { + return this.unifiedSubstitutionData.get(serviceTemplateName).getHandledNestedComputeNodeTemplateIndex(computeType); + } + + public void updateHandledComputeType(String serviceTemplateName, String handledComputeType, String nestedServiceTemplateFileName) { + String globalSTName = ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + this.unifiedSubstitutionData.putIfAbsent(globalSTName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(globalSTName).addHandledComputeType(handledComputeType); + this.unifiedSubstitutionData.get(globalSTName).addHandlesNestedServiceTemplate(nestedServiceTemplateFileName); + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addHandlesNestedServiceTemplate(nestedServiceTemplateFileName); + } + + public void addHandledComputeTypeInServiceTemplate(String serviceTemplateName, String handledComputeType) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addHandledComputeType(handledComputeType); + } + + public boolean isComputeTypeHandledInServiceTemplate(String serviceTemplateName, String computeType) { + return !Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName)) && this.unifiedSubstitutionData.get(serviceTemplateName) + .isComputeTypeHandledInServiceTemplate(computeType); + } + + public boolean isNestedServiceTemplateWasHandled(String serviceTemplateName, String nestedServiceTemplateFileName) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return false; + } + return this.unifiedSubstitutionData.get(serviceTemplateName).isNestedServiceTemplateWasHandled(nestedServiceTemplateFileName); + } + + public Set<String> getAllRelatedNestedNodeTypeIds() { + String globalName = "GlobalSubstitutionTypes"; + if (Objects.isNull(this.unifiedSubstitutionData) || Objects.isNull(this.unifiedSubstitutionData.get(globalName))) { + return new HashSet<>(); + } + return this.unifiedSubstitutionData.get(globalName).getAllRelatedNestedNodeTypeIds(); + } + + public boolean isUnifiedHandledServiceTemplate(ServiceTemplate serviceTemplate) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + return unifiedHandledServiceTemplates.contains(serviceTemplateFileName); + } + + public void addUnifiedHandledServiceTeamplte(ServiceTemplate serviceTemplate) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + this.unifiedHandledServiceTemplates.add(serviceTemplateFileName); + } + + public boolean isNestedNodeWasHandled(String serviceTemplateName, String nestedNodeTemplateId) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return false; + } + return this.unifiedSubstitutionData.get(serviceTemplateName).isNestedNodeWasHandled(nestedNodeTemplateId); + } + + public void addNestedNodeAsHandled(String serviceTemplateName, String nestedNodeTemplateId) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addHandledNestedNodes(nestedNodeTemplateId); + } + + public void updateUsedTimesForNestedComputeNodeType(String serviceTemplateName, String computeType) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).updateUsedTimesForNestedComputeNodeType(computeType); + } + + public int getGlobalNodeTypeIndex(String serviceTemplateName, String computeType) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return 0; + } + return this.unifiedSubstitutionData.get(serviceTemplateName).getGlobalNodeTypeIndex(computeType); + } + + public void addNewPropertyIdToNodeTemplate(String serviceTemplateName, String newPropertyId, Object origPropertyValue) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addNewPropertyIdToNodeTemplate(newPropertyId, origPropertyValue); + } + + public Optional<Object> getNewPropertyInputParamId(String serviceTemplateName, String newPropertyId) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return Optional.empty(); + } + return this.unifiedSubstitutionData.get(serviceTemplateName).getNewPropertyInputParam(newPropertyId); + } + + public Map<String, Object> getAllNewPropertyInputParamIdsPerNodeTenplateId(String serviceTemplateName) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return new HashMap<>(); + } + return this.unifiedSubstitutionData.get(serviceTemplateName).getAllNewPropertyInputParamIds(); + } + + public boolean isServiceTemplateWithoutNodeTemplatesSection(String serviceTemplateName) { + return Objects.nonNull(serviceTemplateName) && serviceTemplatesWithoutNodeTemplateSection.contains(serviceTemplateName); + } + + public void addServiceTemplateWithoutNodeTemplates(String serviceTemplateName) { + this.serviceTemplatesWithoutNodeTemplateSection.add(serviceTemplateName); + } + + public void addNestedNodeTemplateIdPointsToStWithoutNodeTemplates(String nodeTemplateId) { + this.nodeTemplateIdsPointingToStWithoutNodeTemplates.add(nodeTemplateId); + } + + public boolean isNodeTemplateIdPointsToStWithoutNodeTemplates(String nodeTemplateId) { + return Objects.nonNull(nodeTemplateId) && nodeTemplateIdsPointingToStWithoutNodeTemplates.contains(nodeTemplateId); + } + + public void updateRequirementAssignmentIdIndex(String serviceTemplateName, String nodeTemplateId, String requirementId) { + requirementIdAppearanceInNodeTemplate.putIfAbsent(serviceTemplateName, new HashMap<>()); + requirementIdAppearanceInNodeTemplate.get(serviceTemplateName).putIfAbsent(nodeTemplateId, new HashMap<>()); + Map<String, Integer> requirementIdToAppearance = requirementIdAppearanceInNodeTemplate.get(serviceTemplateName).get(nodeTemplateId); + if (requirementIdToAppearance.containsKey(requirementId)) { + requirementIdToAppearance.put(requirementId, requirementIdToAppearance.get(requirementId) + 1); + } else { + requirementIdToAppearance.put(requirementId, 0); + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ContrailServiceInstanceTo.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ContrailServiceInstanceTo.java index 99b3f502b4..1dbef6b992 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ContrailServiceInstanceTo.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ContrailServiceInstanceTo.java @@ -13,22 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; public class ContrailServiceInstanceTo { + private final ServiceTemplate nestedSubstitutionServiceTemplate; private final NodeTemplate substitutedNodeTemplate; private final String heatStackGroupKey; private final boolean orderedInterfaces; private final String computeNodeTemplateId; - public ContrailServiceInstanceTo(ServiceTemplate nestedSubstitutionServiceTemplate, - NodeTemplate substitutedNodeTemplate, String heatStackGroupKey, - boolean orderedInterfaces, String computeNodeTemplateId) { + public ContrailServiceInstanceTo(ServiceTemplate nestedSubstitutionServiceTemplate, NodeTemplate substitutedNodeTemplate, + String heatStackGroupKey, boolean orderedInterfaces, String computeNodeTemplateId) { this.nestedSubstitutionServiceTemplate = nestedSubstitutionServiceTemplate; this.substitutedNodeTemplate = substitutedNodeTemplate; this.heatStackGroupKey = heatStackGroupKey; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/FileDataCollection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/FileDataCollection.java index b156078430..5f78e750ad 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/FileDataCollection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/FileDataCollection.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,119 +17,116 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; - -import org.openecomp.sdc.heat.datatypes.manifest.FileData; - import java.util.ArrayList; import java.util.Collection; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; public class FileDataCollection { - Collection<FileData> baseFiles; - Collection<FileData> addOnFiles; - Collection<FileData> nestedFiles; - Collection<FileData> artifactFiles; - Collection<FileData> HelmFiles; - - public Collection<FileData> getBaseFile() { - return baseFiles; - } - - public Collection<FileData> getHelmFile() { - return HelmFiles; - } - - public void setBaseFile(Collection<FileData> baseFiles) { - this.baseFiles = baseFiles; - } - - public Collection<FileData> getAddOnFiles() { - return addOnFiles; - } - - public void setAddOnFiles(Collection<FileData> addOnFiles) { - this.addOnFiles = addOnFiles; - } - - public Collection<FileData> getNestedFiles() { - return nestedFiles; - } - - public void setNestedFiles(Collection<FileData> nestedFiles) { - this.nestedFiles = nestedFiles; - } - - public Collection<FileData> getBaseFiles() { - return baseFiles; - } - - public void setBaseFiles(Collection<FileData> baseFiles) { - this.baseFiles = baseFiles; - } - - public Collection<FileData> getArtifactFiles() { - return artifactFiles; - } - - public void setArtifactFiles(Collection<FileData> artifactFiles) { - this.artifactFiles = artifactFiles; - } - - /** - * Add add on files. - * - * @param addonFile the addon file - */ - public void addAddOnFiles(FileData addonFile) { - if (this.addOnFiles == null) { - this.addOnFiles = new ArrayList<>(); - } - this.addOnFiles.add(addonFile); - } - - /** - * Add nested files. - * - * @param nestedFile the nested file - */ - public void addNestedFiles(FileData nestedFile) { - if (this.nestedFiles == null) { - this.nestedFiles = new ArrayList<>(); - } - this.nestedFiles.add(nestedFile); - } - - /** - * Add base files. - * - * @param baseFile the base file - */ - public void addBaseFiles(FileData baseFile) { - if (this.baseFiles == null) { - this.baseFiles = new ArrayList<>(); - } - this.baseFiles.add(baseFile); - } - - public void addHelmFiles(FileData helmFile) { - if (this.HelmFiles == null) { - this.HelmFiles = new ArrayList<>(); - } - this.HelmFiles.add(helmFile); - } - - /** - * Add artifact files. - * - * @param artifactFile the artifact file - */ - public void addArtifactFiles(FileData artifactFile) { - if (this.artifactFiles == null) { - this.artifactFiles = new ArrayList<>(); - } - this.artifactFiles.add(artifactFile); - } + Collection<FileData> baseFiles; + Collection<FileData> addOnFiles; + Collection<FileData> nestedFiles; + Collection<FileData> artifactFiles; + Collection<FileData> HelmFiles; + + public Collection<FileData> getBaseFile() { + return baseFiles; + } + + public void setBaseFile(Collection<FileData> baseFiles) { + this.baseFiles = baseFiles; + } + + public Collection<FileData> getHelmFile() { + return HelmFiles; + } + + public Collection<FileData> getAddOnFiles() { + return addOnFiles; + } + + public void setAddOnFiles(Collection<FileData> addOnFiles) { + this.addOnFiles = addOnFiles; + } + + public Collection<FileData> getNestedFiles() { + return nestedFiles; + } + + public void setNestedFiles(Collection<FileData> nestedFiles) { + this.nestedFiles = nestedFiles; + } + + public Collection<FileData> getBaseFiles() { + return baseFiles; + } + + public void setBaseFiles(Collection<FileData> baseFiles) { + this.baseFiles = baseFiles; + } + + public Collection<FileData> getArtifactFiles() { + return artifactFiles; + } + + public void setArtifactFiles(Collection<FileData> artifactFiles) { + this.artifactFiles = artifactFiles; + } + + /** + * Add add on files. + * + * @param addonFile the addon file + */ + public void addAddOnFiles(FileData addonFile) { + if (this.addOnFiles == null) { + this.addOnFiles = new ArrayList<>(); + } + this.addOnFiles.add(addonFile); + } + + /** + * Add nested files. + * + * @param nestedFile the nested file + */ + public void addNestedFiles(FileData nestedFile) { + if (this.nestedFiles == null) { + this.nestedFiles = new ArrayList<>(); + } + this.nestedFiles.add(nestedFile); + } + + /** + * Add base files. + * + * @param baseFile the base file + */ + public void addBaseFiles(FileData baseFile) { + if (this.baseFiles == null) { + this.baseFiles = new ArrayList<>(); + } + this.baseFiles.add(baseFile); + } + + public void addHelmFiles(FileData helmFile) { + if (this.HelmFiles == null) { + this.HelmFiles = new ArrayList<>(); + } + this.HelmFiles.add(helmFile); + } + + /** + * Add artifact files. + * + * @param artifactFile the artifact file + */ + public void addArtifactFiles(FileData artifactFile) { + if (this.artifactFiles == null) { + this.artifactFiles = new ArrayList<>(); + } + this.artifactFiles.add(artifactFile); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java index 24eef115e2..5cfe9185d0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,55 +17,53 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; - import org.openecomp.sdc.heat.datatypes.manifest.FileData; - public class ResourceFileDataAndIDs { - private String resourceId; - private String translatedResourceId; - private FileData fileData; - public ResourceFileDataAndIDs() { - } + private String resourceId; + private String translatedResourceId; + private FileData fileData; + + public ResourceFileDataAndIDs() { + } - /** - * Instantiates a new Resource file data and i ds. - * - * @param resourceId the resource id - * @param translatedResourceId the translated resource id - * @param fileData the file data - */ - public ResourceFileDataAndIDs(String resourceId, String translatedResourceId, FileData fileData) { - this.resourceId = resourceId; - this.translatedResourceId = translatedResourceId; - this.fileData = fileData; - } + /** + * Instantiates a new Resource file data and i ds. + * + * @param resourceId the resource id + * @param translatedResourceId the translated resource id + * @param fileData the file data + */ + public ResourceFileDataAndIDs(String resourceId, String translatedResourceId, FileData fileData) { + this.resourceId = resourceId; + this.translatedResourceId = translatedResourceId; + this.fileData = fileData; + } - public String getResourceId() { - return resourceId; - } + public String getResourceId() { + return resourceId; + } - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } - public String getTranslatedResourceId() { - return translatedResourceId; - } + public String getTranslatedResourceId() { + return translatedResourceId; + } - public void setTranslatedResourceId(String translatedResourceId) { - this.translatedResourceId = translatedResourceId; - } + public void setTranslatedResourceId(String translatedResourceId) { + this.translatedResourceId = translatedResourceId; + } - public FileData getFileData() { - return fileData; - } + public FileData getFileData() { + return fileData; + } - public void setFileData(FileData fileData) { - this.fileData = fileData; - } + public void setFileData(FileData fileData) { + this.fileData = fileData; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java index 617618c822..e754a43083 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,116 +17,108 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; - import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; public class TranslateTo { - private String heatFileName; - private ServiceTemplate serviceTemplate; - private HeatOrchestrationTemplate heatOrchestrationTemplate; - private Resource resource; - private String resourceId; - private String translatedId; - private TranslationContext context; - - public TranslateTo() { - } - - /** - * Instantiates a new Translate to. - * - * @param heatFileName the heat file name - * @param serviceTemplate the service template - * @param heatOrchestrationTemplate the heat orchestration template - * @param resource the resource - * @param resourceId the resource id - * @param translatedId the translated id - * @param context the context - */ - public TranslateTo(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, Resource resource, - String resourceId, String translatedId, TranslationContext context) { - this.heatFileName = heatFileName; - this.serviceTemplate = serviceTemplate; - this.heatOrchestrationTemplate = heatOrchestrationTemplate; - this.resource = resource; - this.resourceId = resourceId; - this.translatedId = translatedId; - this.context = context; - } - - public String getHeatFileName() { - return heatFileName; - } - - public void setHeatFileName(String heatFileName) { - this.heatFileName = heatFileName; - } - - public ServiceTemplate getServiceTemplate() { - return serviceTemplate; - } - - public void setServiceTemplate(ServiceTemplate serviceTemplate) { - this.serviceTemplate = serviceTemplate; - } - - public HeatOrchestrationTemplate getHeatOrchestrationTemplate() { - return heatOrchestrationTemplate; - } - - public void setHeatOrchestrationTemplate(HeatOrchestrationTemplate heatOrchestrationTemplate) { - this.heatOrchestrationTemplate = heatOrchestrationTemplate; - } - - public Resource getResource() { - return resource; - } - - public void setResource(Resource resource) { - this.resource = resource; - } - - public String getResourceId() { - return resourceId; - } - - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } - - public String getTranslatedId() { - return translatedId; - } - - public void setTranslatedId(String translatedId) { - this.translatedId = translatedId; - } - - public TranslationContext getContext() { - return context; - } - - public void setContext(TranslationContext context) { - this.context = context; - } - - @Override - public String toString() { - return "TranslateTo{" - + "heatFileName='" + heatFileName + '\'' - + ", serviceTemplate=" + serviceTemplate - + ", heatOrchestrationTemplate=" + heatOrchestrationTemplate - + ", resource=" + resource - + ", resourceId='" + resourceId + '\'' - + ", translatedId='" + translatedId + '\'' - + ", context=" + context - + '}'; - } + + private String heatFileName; + private ServiceTemplate serviceTemplate; + private HeatOrchestrationTemplate heatOrchestrationTemplate; + private Resource resource; + private String resourceId; + private String translatedId; + private TranslationContext context; + + public TranslateTo() { + } + + /** + * Instantiates a new Translate to. + * + * @param heatFileName the heat file name + * @param serviceTemplate the service template + * @param heatOrchestrationTemplate the heat orchestration template + * @param resource the resource + * @param resourceId the resource id + * @param translatedId the translated id + * @param context the context + */ + public TranslateTo(String heatFileName, ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, Resource resource, + String resourceId, String translatedId, TranslationContext context) { + this.heatFileName = heatFileName; + this.serviceTemplate = serviceTemplate; + this.heatOrchestrationTemplate = heatOrchestrationTemplate; + this.resource = resource; + this.resourceId = resourceId; + this.translatedId = translatedId; + this.context = context; + } + + public String getHeatFileName() { + return heatFileName; + } + + public void setHeatFileName(String heatFileName) { + this.heatFileName = heatFileName; + } + + public ServiceTemplate getServiceTemplate() { + return serviceTemplate; + } + + public void setServiceTemplate(ServiceTemplate serviceTemplate) { + this.serviceTemplate = serviceTemplate; + } + + public HeatOrchestrationTemplate getHeatOrchestrationTemplate() { + return heatOrchestrationTemplate; + } + + public void setHeatOrchestrationTemplate(HeatOrchestrationTemplate heatOrchestrationTemplate) { + this.heatOrchestrationTemplate = heatOrchestrationTemplate; + } + + public Resource getResource() { + return resource; + } + + public void setResource(Resource resource) { + this.resource = resource; + } + + public String getResourceId() { + return resourceId; + } + + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + + public String getTranslatedId() { + return translatedId; + } + + public void setTranslatedId(String translatedId) { + this.translatedId = translatedId; + } + + public TranslationContext getContext() { + return context; + } + + public void setContext(TranslationContext context) { + this.context = context; + } + + @Override + public String toString() { + return "TranslateTo{" + "heatFileName='" + heatFileName + '\'' + ", serviceTemplate=" + serviceTemplate + ", heatOrchestrationTemplate=" + + heatOrchestrationTemplate + ", resource=" + resource + ", resourceId='" + resourceId + '\'' + ", translatedId='" + translatedId + '\'' + + ", context=" + context + '}'; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslatedHeatResource.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslatedHeatResource.java index da46e56018..5be053cbef 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslatedHeatResource.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslatedHeatResource.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; import org.openecomp.sdc.heat.datatypes.model.Resource; public class TranslatedHeatResource { - private String translatedId; - private Resource heatResource; - public TranslatedHeatResource(String translatedId, Resource heatResource) { - this.translatedId = translatedId; - this.heatResource = heatResource; - } + private String translatedId; + private Resource heatResource; + + public TranslatedHeatResource(String translatedId, Resource heatResource) { + this.translatedId = translatedId; + this.heatResource = heatResource; + } - public String getTranslatedId() { - return translatedId; - } + public String getTranslatedId() { + return translatedId; + } - public void setTranslatedId(String translatedId) { - this.translatedId = translatedId; - } + public void setTranslatedId(String translatedId) { + this.translatedId = translatedId; + } - public Resource getHeatResource() { - return heatResource; - } + public Resource getHeatResource() { + return heatResource; + } - public void setHeatResource(Resource heatResource) { - this.heatResource = heatResource; - } + public void setHeatResource(Resource heatResource) { + this.heatResource = heatResource; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java index 235e00fab4..79d00c3048 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java @@ -25,32 +25,31 @@ import org.onap.sdc.tosca.datatypes.model.NodeTemplate; * Created by Talio on 4/4/2017. */ public class NodeTemplateInformation { - UnifiedCompositionEntity unifiedCompositionEntity; - private NodeTemplate nodeTemplate; - - public NodeTemplateInformation(){} - - public NodeTemplateInformation( - UnifiedCompositionEntity unifiedCompositionEntity, - NodeTemplate nodeTemplate) { - this.unifiedCompositionEntity = unifiedCompositionEntity; - this.nodeTemplate = nodeTemplate; - } - - public UnifiedCompositionEntity getUnifiedCompositionEntity() { - return unifiedCompositionEntity; - } - - public void setUnifiedCompositionEntity( - UnifiedCompositionEntity unifiedCompositionEntity) { - this.unifiedCompositionEntity = unifiedCompositionEntity; - } - - public NodeTemplate getNodeTemplate() { - return nodeTemplate; - } - - public void setNodeTemplate(NodeTemplate nodeTemplate) { - this.nodeTemplate = nodeTemplate; - } + + UnifiedCompositionEntity unifiedCompositionEntity; + private NodeTemplate nodeTemplate; + + public NodeTemplateInformation() { + } + + public NodeTemplateInformation(UnifiedCompositionEntity unifiedCompositionEntity, NodeTemplate nodeTemplate) { + this.unifiedCompositionEntity = unifiedCompositionEntity; + this.nodeTemplate = nodeTemplate; + } + + public UnifiedCompositionEntity getUnifiedCompositionEntity() { + return unifiedCompositionEntity; + } + + public void setUnifiedCompositionEntity(UnifiedCompositionEntity unifiedCompositionEntity) { + this.unifiedCompositionEntity = unifiedCompositionEntity; + } + + public NodeTemplate getNodeTemplate() { + return nodeTemplate; + } + + public void setNodeTemplate(NodeTemplate nodeTemplate) { + this.nodeTemplate = nodeTemplate; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java index 08db3be2a9..9f14737dd9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java @@ -13,121 +13,112 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition; +import java.util.ArrayList; +import java.util.List; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedTemplateConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.SubInterfaceTemplateConsolidationData; -import java.util.ArrayList; -import java.util.List; - /** * The type Unified composition data. */ public class UnifiedCompositionData { - /** - * The Compute template consolidation data. - */ - private ComputeTemplateConsolidationData computeTemplateConsolidationData; - /** - * The Port template consolidation data list. - */ - private List<PortTemplateConsolidationData> portTemplateConsolidationDataList; - private List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList; + /** + * The Compute template consolidation data. + */ + private ComputeTemplateConsolidationData computeTemplateConsolidationData; + /** + * The Port template consolidation data list. + */ + private List<PortTemplateConsolidationData> portTemplateConsolidationDataList; + private List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList; + private NestedTemplateConsolidationData nestedTemplateConsolidationData; - private NestedTemplateConsolidationData nestedTemplateConsolidationData; - - /** - * Gets compute template consolidation data. - * - * @return the compute template consolidation data - */ - public ComputeTemplateConsolidationData getComputeTemplateConsolidationData() { - return computeTemplateConsolidationData; - } + /** + * Gets compute template consolidation data. + * + * @return the compute template consolidation data + */ + public ComputeTemplateConsolidationData getComputeTemplateConsolidationData() { + return computeTemplateConsolidationData; + } - /** - * Sets compute template consolidation data. - * - * @param computeTemplateConsolidationData the compute template consolidation data - */ - public void setComputeTemplateConsolidationData( - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - this.computeTemplateConsolidationData = computeTemplateConsolidationData; - } + /** + * Sets compute template consolidation data. + * + * @param computeTemplateConsolidationData the compute template consolidation data + */ + public void setComputeTemplateConsolidationData(ComputeTemplateConsolidationData computeTemplateConsolidationData) { + this.computeTemplateConsolidationData = computeTemplateConsolidationData; + } - /** - * Gets port template consolidation data list. - * - * @return the port template consolidation data list - */ - public List<PortTemplateConsolidationData> getPortTemplateConsolidationDataList() { - return portTemplateConsolidationDataList; - } + /** + * Gets port template consolidation data list. + * + * @return the port template consolidation data list + */ + public List<PortTemplateConsolidationData> getPortTemplateConsolidationDataList() { + return portTemplateConsolidationDataList; + } - /** - * Sets port template consolidation data list. - * - * @param portTemplateConsolidationDataList the port template consolidation data list - */ - public void setPortTemplateConsolidationDataList( - List<PortTemplateConsolidationData> portTemplateConsolidationDataList) { - this.portTemplateConsolidationDataList = portTemplateConsolidationDataList; - } + /** + * Sets port template consolidation data list. + * + * @param portTemplateConsolidationDataList the port template consolidation data list + */ + public void setPortTemplateConsolidationDataList(List<PortTemplateConsolidationData> portTemplateConsolidationDataList) { + this.portTemplateConsolidationDataList = portTemplateConsolidationDataList; + } - /** - * Add port consolidation data. - * - * @param portTemplateConsolidationData the port consolidation data - */ - public void addPortTemplateConsolidationData( - PortTemplateConsolidationData portTemplateConsolidationData) { - if (this.portTemplateConsolidationDataList == null) { - this.portTemplateConsolidationDataList = new ArrayList<>(); + /** + * Add port consolidation data. + * + * @param portTemplateConsolidationData the port consolidation data + */ + public void addPortTemplateConsolidationData(PortTemplateConsolidationData portTemplateConsolidationData) { + if (this.portTemplateConsolidationDataList == null) { + this.portTemplateConsolidationDataList = new ArrayList<>(); + } + this.portTemplateConsolidationDataList.add(portTemplateConsolidationData); } - this.portTemplateConsolidationDataList.add(portTemplateConsolidationData); - } - /** - * Gets sub interface template consolidation data list. - * - * @return the sub interface template consolidation data list - */ - public List<SubInterfaceTemplateConsolidationData> getSubInterfaceTemplateConsolidationDataList() { - return subInterfaceTemplateConsolidationDataList; - } + /** + * Gets sub interface template consolidation data list. + * + * @return the sub interface template consolidation data list + */ + public List<SubInterfaceTemplateConsolidationData> getSubInterfaceTemplateConsolidationDataList() { + return subInterfaceTemplateConsolidationDataList; + } - /** - * Sets sub interface template consolidation data list. - * - * @param subInterfaceTemplateConsolidationDataList the sub interface template consolidation data - * list - */ - public void setSubInterfaceTemplateConsolidationDataList( - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList) { - this.subInterfaceTemplateConsolidationDataList = subInterfaceTemplateConsolidationDataList; - } + /** + * Sets sub interface template consolidation data list. + * + * @param subInterfaceTemplateConsolidationDataList the sub interface template consolidation data list + */ + public void setSubInterfaceTemplateConsolidationDataList(List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList) { + this.subInterfaceTemplateConsolidationDataList = subInterfaceTemplateConsolidationDataList; + } - /** - * Gets nested template consolidation data. - * - * @return the nested template consolidation data - */ - public NestedTemplateConsolidationData getNestedTemplateConsolidationData() { - return nestedTemplateConsolidationData; - } + /** + * Gets nested template consolidation data. + * + * @return the nested template consolidation data + */ + public NestedTemplateConsolidationData getNestedTemplateConsolidationData() { + return nestedTemplateConsolidationData; + } - /** - * Sets nested template consolidation data. - * - * @param nestedTemplateConsolidationData the nested template consolidation data - */ - public void setNestedTemplateConsolidationData( - NestedTemplateConsolidationData nestedTemplateConsolidationData) { - this.nestedTemplateConsolidationData = nestedTemplateConsolidationData; - } + /** + * Sets nested template consolidation data. + * + * @param nestedTemplateConsolidationData the nested template consolidation data + */ + public void setNestedTemplateConsolidationData(NestedTemplateConsolidationData nestedTemplateConsolidationData) { + this.nestedTemplateConsolidationData = nestedTemplateConsolidationData; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java index 58a9092616..0484d2f7be 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java @@ -13,23 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition; public enum UnifiedCompositionEntity { - COMPUTE("Compute"), - PORT("Port"), - NESTED("Nested"), - SUB_INTERFACE("SubInterface"), - OTHER("Other"); - - private String displayName; + COMPUTE("Compute"), PORT("Port"), NESTED("Nested"), SUB_INTERFACE("SubInterface"), OTHER("Other"); + private String displayName; - UnifiedCompositionEntity(String displayName) { - this.displayName = displayName; - } + UnifiedCompositionEntity(String displayName) { + this.displayName = displayName; + } - public String getDisplayName() { - return displayName; - } + public String getDisplayName() { + return displayName; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java index e8c9060ca5..44311041c8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java @@ -24,9 +24,7 @@ package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composit * @since March 02, 2017. */ public enum UnifiedCompositionMode { - SingleSubstitution, - ScalingInstances, - // todo - support B1 SingleSubstitution, but create diff types/services vm_type+<index> - CatalogInstance, - NestedSingleCompute; + SingleSubstitution, ScalingInstances, + // todo - support B1 SingleSubstitution, but create diff types/services vm_type+<index> + CatalogInstance, NestedSingleCompute; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java index dd9b69f786..3749c942b4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java @@ -26,186 +26,164 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; public class UnifiedSubstitutionData { - //Key - node template id, Value - related abstract node template id - private Map<String, String> nodesRelatedAbstractNode = new HashMap<>(); - //Key - node template id, Value - related node template id in the substitution service template - private Map<String, String> nodesRelatedSubstitutionServiceTemplateNode = new HashMap<>(); - private Map<String, NodeTemplateInformation> cleanedNodeTemplates = new HashMap<>(); - //Key - nested node template id, Value - related unified nested node template id - private Map<String, String> nestedNodeTemplateRelatedUnifiedTranslatedId = new HashMap<>(); - //Key - nested node type id, Value - related unified nested node template id - private Map<String, String> nestedNodeTypeRelatedUnifiedTranslatedId = new HashMap<>(); - //Key - handled compute type, Value - number of times it was handled - private Map<String, Integer> handledComputeTypesInNestedSubstitutionTemplate = - new HashMap<>(); - //Key - nested compute type, Value - list of nested files that the compute type is present - private Map<String, Integer> handledNestedComputeTypesNestedFiles = new HashMap<>(); - //Key - new property id, Value - orig property value - private Map<String, Object> newParameterIdsToPropertiesFromOrigNodeTemplate = new HashMap<>(); - //handled nested files - private Set<String> handledNestedFiles = new HashSet<>(); - //handled nested nodes - private Set<String> handledNestedNodes = new HashSet<>(); - - public Map<String, String> getNodesRelatedAbstractNode() { - return nodesRelatedAbstractNode; - } - - public void setNodesRelatedAbstractNode( - Map<String, String> nodesRelatedAbstractNode) { - this.nodesRelatedAbstractNode = nodesRelatedAbstractNode; - } - - public void addHandledNestedNodes(String handledNestedNodeId) { - this.handledNestedNodes.add(handledNestedNodeId); - } - - public Map<String, String> getNodesRelatedSubstitutionServiceTemplateNode() { - return nodesRelatedSubstitutionServiceTemplateNode; - } - - public void setNodesRelatedSubstitutionServiceTemplateNode( - Map<String, String> nodesRelatedSubstitutionServiceTemplateNode) { - this.nodesRelatedSubstitutionServiceTemplateNode = nodesRelatedSubstitutionServiceTemplateNode; - } - - public String getNodeRelatedAbstractNode(String origNodeId) { - return this.nodesRelatedAbstractNode.get(origNodeId); - } - - public Collection<String> getAllRelatedAbstractNodeIds() { - return this.nodesRelatedAbstractNode.values(); - } - - public Collection<String> getAllUnifiedNestedNodeTemplateIds() { - return this.nestedNodeTemplateRelatedUnifiedTranslatedId.values(); - } - - /** - * Add cleaned node template. - * - * @param nodeTemplateId the node template id - * @param unifiedCompositionEntity the unified composition entity - * @param nodeTemplate the node template - */ - public void addCleanedNodeTemplate(String nodeTemplateId, - UnifiedCompositionEntity unifiedCompositionEntity, - NodeTemplate nodeTemplate) { - NodeTemplateInformation nodeTemplateInformation = new NodeTemplateInformation( - unifiedCompositionEntity, nodeTemplate); - this.cleanedNodeTemplates.putIfAbsent(nodeTemplateId, nodeTemplateInformation); - } - - public NodeTemplate getCleanedNodeTemplate(String nodeTemplateId) { - return this.cleanedNodeTemplates.get(nodeTemplateId).getNodeTemplate().clone(); - } - - public UnifiedCompositionEntity getCleanedNodeTemplateCompositionEntity(String nodeTemplateId) { - return this.cleanedNodeTemplates.get(nodeTemplateId).getUnifiedCompositionEntity(); - } - - public void addUnifiedNestedNodeTemplateId(String nestedNodeTemplateId, - String unifiedNestedNodeRelatedId) { - this.nestedNodeTemplateRelatedUnifiedTranslatedId - .put(nestedNodeTemplateId, unifiedNestedNodeRelatedId); - } - - public Optional<String> getUnifiedNestedNodeTemplateId(String nestedNodeTemplateId) { - return this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId) == null - ? Optional.empty() - : Optional.of(this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId)); - } - - public void addUnifiedNestedNodeTypeId(String nestedNodeTypeId, - String unifiedNestedNodeRelatedId) { - this.nestedNodeTypeRelatedUnifiedTranslatedId.put(nestedNodeTypeId, unifiedNestedNodeRelatedId); - } - - public Optional<String> getUnifiedNestedNodeTypeId(String nestedNodeTypeId) { - return this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId) == null ? Optional - .empty() - : Optional.of(this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId)); - } - - public Set<String> getAllRelatedNestedNodeTypeIds(){ - if(MapUtils.isEmpty(nestedNodeTypeRelatedUnifiedTranslatedId)){ - return new HashSet<>(); - } - return new HashSet<>(this.nestedNodeTypeRelatedUnifiedTranslatedId.values()); - } - - public void addHandledComputeType(String handledComputeType) { - - if (this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(handledComputeType)) { - Integer timesHandled = - this.handledComputeTypesInNestedSubstitutionTemplate.get(handledComputeType); - this.handledComputeTypesInNestedSubstitutionTemplate - .put(handledComputeType, timesHandled + 1); - } else { - //this.handledNestedFiles.add(nestedServiceTemplateFileName); - handledComputeTypesInNestedSubstitutionTemplate.put(handledComputeType, 0); - } - } - - public boolean isComputeTypeHandledInServiceTemplate(String computeType) { - return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType); - } - - public int getHandledNestedComputeNodeTemplateIndex(String computeType) { - return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType) ? - this.handledComputeTypesInNestedSubstitutionTemplate.get(computeType) : 0; - } - - public void addHandlesNestedServiceTemplate(String nestedServiceTemplateFileName){ - this.handledNestedFiles.add(nestedServiceTemplateFileName); - } - - public boolean isNestedServiceTemplateWasHandled(String nestedServiceTemplateFileName) { - return this.handledNestedFiles.contains(nestedServiceTemplateFileName); - } - - public void updateUsedTimesForNestedComputeNodeType(String computeType) { - this.handledNestedComputeTypesNestedFiles.putIfAbsent(computeType, 0); - - Integer usedNumber = this.handledNestedComputeTypesNestedFiles.get(computeType); - this.handledNestedComputeTypesNestedFiles.put(computeType, usedNumber + 1); - - } - - public int getGlobalNodeTypeIndex(String computeType) { - return Objects.isNull(this.handledNestedComputeTypesNestedFiles.get(computeType)) - || this.handledNestedComputeTypesNestedFiles.get(computeType)== 0 ? 0 - : this.handledNestedComputeTypesNestedFiles.get(computeType); - } - - public boolean isNestedNodeWasHandled(String nestedNodeId) { - return this.handledNestedNodes.contains(nestedNodeId); - } - - - public Map<String, Object> getAllNewPropertyInputParamIds(){ - return this.newParameterIdsToPropertiesFromOrigNodeTemplate; - } - - public void addNewPropertyIdToNodeTemplate(String newPropertyId, - Object origPropertyValue){ - if(!newParameterIdsToPropertiesFromOrigNodeTemplate.containsKey(newPropertyId)) { - newParameterIdsToPropertiesFromOrigNodeTemplate.put(newPropertyId, origPropertyValue); + //Key - node template id, Value - related abstract node template id + private Map<String, String> nodesRelatedAbstractNode = new HashMap<>(); + //Key - node template id, Value - related node template id in the substitution service template + private Map<String, String> nodesRelatedSubstitutionServiceTemplateNode = new HashMap<>(); + private Map<String, NodeTemplateInformation> cleanedNodeTemplates = new HashMap<>(); + //Key - nested node template id, Value - related unified nested node template id + private Map<String, String> nestedNodeTemplateRelatedUnifiedTranslatedId = new HashMap<>(); + //Key - nested node type id, Value - related unified nested node template id + private Map<String, String> nestedNodeTypeRelatedUnifiedTranslatedId = new HashMap<>(); + //Key - handled compute type, Value - number of times it was handled + private Map<String, Integer> handledComputeTypesInNestedSubstitutionTemplate = new HashMap<>(); + //Key - nested compute type, Value - list of nested files that the compute type is present + private Map<String, Integer> handledNestedComputeTypesNestedFiles = new HashMap<>(); + //Key - new property id, Value - orig property value + private Map<String, Object> newParameterIdsToPropertiesFromOrigNodeTemplate = new HashMap<>(); + //handled nested files + private Set<String> handledNestedFiles = new HashSet<>(); + //handled nested nodes + private Set<String> handledNestedNodes = new HashSet<>(); + + public Map<String, String> getNodesRelatedAbstractNode() { + return nodesRelatedAbstractNode; + } + + public void setNodesRelatedAbstractNode(Map<String, String> nodesRelatedAbstractNode) { + this.nodesRelatedAbstractNode = nodesRelatedAbstractNode; } - } - public Optional<Object> getNewPropertyInputParam(String newPropertyId){ - if(!newParameterIdsToPropertiesFromOrigNodeTemplate.containsKey(newPropertyId)){ - return Optional.empty(); + public void addHandledNestedNodes(String handledNestedNodeId) { + this.handledNestedNodes.add(handledNestedNodeId); } - return Optional.of(newParameterIdsToPropertiesFromOrigNodeTemplate.get(newPropertyId)); - } + public Map<String, String> getNodesRelatedSubstitutionServiceTemplateNode() { + return nodesRelatedSubstitutionServiceTemplateNode; + } + public void setNodesRelatedSubstitutionServiceTemplateNode(Map<String, String> nodesRelatedSubstitutionServiceTemplateNode) { + this.nodesRelatedSubstitutionServiceTemplateNode = nodesRelatedSubstitutionServiceTemplateNode; + } + + public String getNodeRelatedAbstractNode(String origNodeId) { + return this.nodesRelatedAbstractNode.get(origNodeId); + } + + public Collection<String> getAllRelatedAbstractNodeIds() { + return this.nodesRelatedAbstractNode.values(); + } + + public Collection<String> getAllUnifiedNestedNodeTemplateIds() { + return this.nestedNodeTemplateRelatedUnifiedTranslatedId.values(); + } + + /** + * Add cleaned node template. + * + * @param nodeTemplateId the node template id + * @param unifiedCompositionEntity the unified composition entity + * @param nodeTemplate the node template + */ + public void addCleanedNodeTemplate(String nodeTemplateId, UnifiedCompositionEntity unifiedCompositionEntity, NodeTemplate nodeTemplate) { + NodeTemplateInformation nodeTemplateInformation = new NodeTemplateInformation(unifiedCompositionEntity, nodeTemplate); + this.cleanedNodeTemplates.putIfAbsent(nodeTemplateId, nodeTemplateInformation); + } + + public NodeTemplate getCleanedNodeTemplate(String nodeTemplateId) { + return this.cleanedNodeTemplates.get(nodeTemplateId).getNodeTemplate().clone(); + } + + public UnifiedCompositionEntity getCleanedNodeTemplateCompositionEntity(String nodeTemplateId) { + return this.cleanedNodeTemplates.get(nodeTemplateId).getUnifiedCompositionEntity(); + } + + public void addUnifiedNestedNodeTemplateId(String nestedNodeTemplateId, String unifiedNestedNodeRelatedId) { + this.nestedNodeTemplateRelatedUnifiedTranslatedId.put(nestedNodeTemplateId, unifiedNestedNodeRelatedId); + } + + public Optional<String> getUnifiedNestedNodeTemplateId(String nestedNodeTemplateId) { + return this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId) == null ? Optional.empty() + : Optional.of(this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId)); + } + + public void addUnifiedNestedNodeTypeId(String nestedNodeTypeId, String unifiedNestedNodeRelatedId) { + this.nestedNodeTypeRelatedUnifiedTranslatedId.put(nestedNodeTypeId, unifiedNestedNodeRelatedId); + } + + public Optional<String> getUnifiedNestedNodeTypeId(String nestedNodeTypeId) { + return this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId) == null ? Optional.empty() + : Optional.of(this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId)); + } + + public Set<String> getAllRelatedNestedNodeTypeIds() { + if (MapUtils.isEmpty(nestedNodeTypeRelatedUnifiedTranslatedId)) { + return new HashSet<>(); + } + return new HashSet<>(this.nestedNodeTypeRelatedUnifiedTranslatedId.values()); + } + + public void addHandledComputeType(String handledComputeType) { + if (this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(handledComputeType)) { + Integer timesHandled = this.handledComputeTypesInNestedSubstitutionTemplate.get(handledComputeType); + this.handledComputeTypesInNestedSubstitutionTemplate.put(handledComputeType, timesHandled + 1); + } else { + //this.handledNestedFiles.add(nestedServiceTemplateFileName); + handledComputeTypesInNestedSubstitutionTemplate.put(handledComputeType, 0); + } + } + + public boolean isComputeTypeHandledInServiceTemplate(String computeType) { + return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType); + } + + public int getHandledNestedComputeNodeTemplateIndex(String computeType) { + return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType) ? this.handledComputeTypesInNestedSubstitutionTemplate + .get(computeType) : 0; + } + + public void addHandlesNestedServiceTemplate(String nestedServiceTemplateFileName) { + this.handledNestedFiles.add(nestedServiceTemplateFileName); + } + + public boolean isNestedServiceTemplateWasHandled(String nestedServiceTemplateFileName) { + return this.handledNestedFiles.contains(nestedServiceTemplateFileName); + } + + public void updateUsedTimesForNestedComputeNodeType(String computeType) { + this.handledNestedComputeTypesNestedFiles.putIfAbsent(computeType, 0); + Integer usedNumber = this.handledNestedComputeTypesNestedFiles.get(computeType); + this.handledNestedComputeTypesNestedFiles.put(computeType, usedNumber + 1); + } + + public int getGlobalNodeTypeIndex(String computeType) { + return Objects.isNull(this.handledNestedComputeTypesNestedFiles.get(computeType)) + || this.handledNestedComputeTypesNestedFiles.get(computeType) == 0 ? 0 : this.handledNestedComputeTypesNestedFiles.get(computeType); + } + + public boolean isNestedNodeWasHandled(String nestedNodeId) { + return this.handledNestedNodes.contains(nestedNodeId); + } + + public Map<String, Object> getAllNewPropertyInputParamIds() { + return this.newParameterIdsToPropertiesFromOrigNodeTemplate; + } + + public void addNewPropertyIdToNodeTemplate(String newPropertyId, Object origPropertyValue) { + if (!newParameterIdsToPropertiesFromOrigNodeTemplate.containsKey(newPropertyId)) { + newParameterIdsToPropertiesFromOrigNodeTemplate.put(newPropertyId, origPropertyValue); + } + } + + public Optional<Object> getNewPropertyInputParam(String newPropertyId) { + if (!newParameterIdsToPropertiesFromOrigNodeTemplate.containsKey(newPropertyId)) { + return Optional.empty(); + } + return Optional.of(newParameterIdsToPropertiesFromOrigNodeTemplate.get(newPropertyId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/CommandImplNames.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/CommandImplNames.java index 8fa2c74b1b..6a8fac6508 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/CommandImplNames.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/CommandImplNames.java @@ -13,18 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands; public class CommandImplNames { - private static final String COMMANDS_IMPL_BASE_PACKAGE = - "org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl"; - - public static final String COMPUTE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = - COMMANDS_IMPL_BASE_PACKAGE + ".ComputeNewNodeTemplateIdGenerator"; - public static final String PORT_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = - COMMANDS_IMPL_BASE_PACKAGE + ".PortNewNodeTemplateIdGenerator"; - public static final String SUB_INTERFACE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = - COMMANDS_IMPL_BASE_PACKAGE + ".SubInterfaceNewNodeTemplateIdGenerator"; + private static final String COMMANDS_IMPL_BASE_PACKAGE = "org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl"; + public static final String COMPUTE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = COMMANDS_IMPL_BASE_PACKAGE + ".ComputeNewNodeTemplateIdGenerator"; + public static final String PORT_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = COMMANDS_IMPL_BASE_PACKAGE + ".PortNewNodeTemplateIdGenerator"; + public static final String SUB_INTERFACE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = + COMMANDS_IMPL_BASE_PACKAGE + ".SubInterfaceNewNodeTemplateIdGenerator"; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/UnifiedSubstitutionNodeTemplateIdGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/UnifiedSubstitutionNodeTemplateIdGenerator.java index a932859807..fd5c05236e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/UnifiedSubstitutionNodeTemplateIdGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/UnifiedSubstitutionNodeTemplateIdGenerator.java @@ -13,13 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to.UnifiedCompositionTo; - import java.util.Optional; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to.UnifiedCompositionTo; public interface UnifiedSubstitutionNodeTemplateIdGenerator { - public Optional<String> generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId); + + public Optional<String> generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/ComputeNewNodeTemplateIdGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/ComputeNewNodeTemplateIdGenerator.java index c39a26c545..f88f7b2002 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/ComputeNewNodeTemplateIdGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/ComputeNewNodeTemplateIdGenerator.java @@ -13,20 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl; +import java.util.Optional; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.UnifiedSubstitutionNodeTemplateIdGenerator; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to.UnifiedCompositionTo; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil; -import java.util.Optional; - public class ComputeNewNodeTemplateIdGenerator implements UnifiedSubstitutionNodeTemplateIdGenerator { - @Override - public Optional<String> generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { - return Optional.ofNullable(UnifiedCompositionUtil.getNewComputeNodeTemplateId( - unifiedCompositionTo.getServiceTemplate(), originalNodeTemplateId)); - } + @Override + public Optional<String> generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { + return Optional + .ofNullable(UnifiedCompositionUtil.getNewComputeNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), originalNodeTemplateId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/PortNewNodeTemplateIdGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/PortNewNodeTemplateIdGenerator.java index 7a49861452..746f435221 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/PortNewNodeTemplateIdGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/PortNewNodeTemplateIdGenerator.java @@ -13,34 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewPortNodeTemplateId; + +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.UnifiedSubstitutionNodeTemplateIdGenerator; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to.UnifiedCompositionTo; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; -import java.util.Objects; -import java.util.Optional; - -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewPortNodeTemplateId; - public class PortNewNodeTemplateIdGenerator implements UnifiedSubstitutionNodeTemplateIdGenerator { - @Override - public Optional<String> generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { - ComputeTemplateConsolidationData connectedComputeConsolidationData = - getConnectedComputeConsolidationData(unifiedCompositionTo.getUnifiedCompositionDataList(), - originalNodeTemplateId); - if (Objects.nonNull(connectedComputeConsolidationData)) { - NodeTemplate connectedComputeNodeTemplate = DataModelUtil.getNodeTemplate(unifiedCompositionTo - .getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); - return Optional.of(getNewPortNodeTemplateId(originalNodeTemplateId, connectedComputeNodeTemplate.getType(), - connectedComputeConsolidationData)); + @Override + public Optional<String> generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { + ComputeTemplateConsolidationData connectedComputeConsolidationData = getConnectedComputeConsolidationData( + unifiedCompositionTo.getUnifiedCompositionDataList(), originalNodeTemplateId); + if (Objects.nonNull(connectedComputeConsolidationData)) { + NodeTemplate connectedComputeNodeTemplate = DataModelUtil + .getNodeTemplate(unifiedCompositionTo.getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); + return Optional + .of(getNewPortNodeTemplateId(originalNodeTemplateId, connectedComputeNodeTemplate.getType(), connectedComputeConsolidationData)); + } + return Optional.empty(); } - return Optional.empty(); - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/SubInterfaceNewNodeTemplateIdGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/SubInterfaceNewNodeTemplateIdGenerator.java index e2e938b83c..82ab669ddb 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/SubInterfaceNewNodeTemplateIdGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/SubInterfaceNewNodeTemplateIdGenerator.java @@ -13,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewSubInterfaceNodeTemplateId; + +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; @@ -25,45 +31,31 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.SubInterfaceTemplateConsolidationData; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewSubInterfaceNodeTemplateId; - public class SubInterfaceNewNodeTemplateIdGenerator implements UnifiedSubstitutionNodeTemplateIdGenerator { - @Override - public Optional<String> generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { - SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationDataById(unifiedCompositionTo.getUnifiedCompositionDataList(), - originalNodeTemplateId); - if (Objects.nonNull(subInterfaceTemplateConsolidationData)) { - String parentPortNodeTemplateId = subInterfaceTemplateConsolidationData.getParentPortNodeTemplateId(); - ComputeTemplateConsolidationData connectedComputeConsolidationData = - getConnectedComputeConsolidationData(unifiedCompositionTo.getUnifiedCompositionDataList(), - parentPortNodeTemplateId); - if (Objects.nonNull(connectedComputeConsolidationData)) { - NodeTemplate connectedComputeNodeTemplate = DataModelUtil.getNodeTemplate(unifiedCompositionTo - .getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); - return Optional.of(getNewSubInterfaceNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), - connectedComputeNodeTemplate.getType(), connectedComputeConsolidationData, - subInterfaceTemplateConsolidationData, unifiedCompositionTo.getContext())); - } + private static SubInterfaceTemplateConsolidationData getSubInterfaceTemplateConsolidationDataById( + List<UnifiedCompositionData> unifiedCompositionDataList, String subInterfaceNodeTemplateId) { + return unifiedCompositionDataList.stream().map(UnifiedCompositionUtil::getSubInterfaceTemplateConsolidationDataList) + .flatMap(Collection::stream).filter( + subInterfaceTemplateConsolidationData -> subInterfaceNodeTemplateId.equals(subInterfaceTemplateConsolidationData.getNodeTemplateId())) + .findFirst().orElse(null); } - return Optional.empty(); - } - private static SubInterfaceTemplateConsolidationData getSubInterfaceTemplateConsolidationDataById( - List<UnifiedCompositionData> unifiedCompositionDataList, - String subInterfaceNodeTemplateId) { - return unifiedCompositionDataList.stream() - .map(UnifiedCompositionUtil::getSubInterfaceTemplateConsolidationDataList) - .flatMap(Collection::stream) - .filter(subInterfaceTemplateConsolidationData -> subInterfaceNodeTemplateId - .equals(subInterfaceTemplateConsolidationData.getNodeTemplateId())) - .findFirst().orElse(null); - } + @Override + public Optional<String> generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { + SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationDataById( + unifiedCompositionTo.getUnifiedCompositionDataList(), originalNodeTemplateId); + if (Objects.nonNull(subInterfaceTemplateConsolidationData)) { + String parentPortNodeTemplateId = subInterfaceTemplateConsolidationData.getParentPortNodeTemplateId(); + ComputeTemplateConsolidationData connectedComputeConsolidationData = getConnectedComputeConsolidationData( + unifiedCompositionTo.getUnifiedCompositionDataList(), parentPortNodeTemplateId); + if (Objects.nonNull(connectedComputeConsolidationData)) { + NodeTemplate connectedComputeNodeTemplate = DataModelUtil + .getNodeTemplate(unifiedCompositionTo.getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); + return Optional.of(getNewSubInterfaceNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), connectedComputeNodeTemplate.getType(), + connectedComputeConsolidationData, subInterfaceTemplateConsolidationData, unifiedCompositionTo.getContext())); + } + } + return Optional.empty(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/to/UnifiedCompositionTo.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/to/UnifiedCompositionTo.java index 6ae6785f3e..30c89accd0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/to/UnifiedCompositionTo.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/to/UnifiedCompositionTo.java @@ -13,73 +13,68 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to; +import java.util.List; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; -import java.util.List; - public class UnifiedCompositionTo { - private ServiceTemplate serviceTemplate; - private ServiceTemplate substitutionServiceTemplate; - private List<UnifiedCompositionData> unifiedCompositionDataList; - private TranslationContext context; - private NodeTemplate nodeTemplate; - public UnifiedCompositionTo(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context, - NodeTemplate nodeTemplate) { - this.serviceTemplate = serviceTemplate; - this.substitutionServiceTemplate = substitutionServiceTemplate; - this.unifiedCompositionDataList = unifiedCompositionDataList; - this.context = context; - this.nodeTemplate = nodeTemplate; - } + private ServiceTemplate serviceTemplate; + private ServiceTemplate substitutionServiceTemplate; + private List<UnifiedCompositionData> unifiedCompositionDataList; + private TranslationContext context; + private NodeTemplate nodeTemplate; + + public UnifiedCompositionTo(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context, NodeTemplate nodeTemplate) { + this.serviceTemplate = serviceTemplate; + this.substitutionServiceTemplate = substitutionServiceTemplate; + this.unifiedCompositionDataList = unifiedCompositionDataList; + this.context = context; + this.nodeTemplate = nodeTemplate; + } - public ServiceTemplate getServiceTemplate() { - return serviceTemplate; - } + public ServiceTemplate getServiceTemplate() { + return serviceTemplate; + } - public void setServiceTemplate(ServiceTemplate serviceTemplate) { - this.serviceTemplate = serviceTemplate; - } + public void setServiceTemplate(ServiceTemplate serviceTemplate) { + this.serviceTemplate = serviceTemplate; + } - public ServiceTemplate getSubstitutionServiceTemplate() { - return substitutionServiceTemplate; - } + public ServiceTemplate getSubstitutionServiceTemplate() { + return substitutionServiceTemplate; + } - public void setSubstitutionServiceTemplate(ServiceTemplate substitutionServiceTemplate) { - this.substitutionServiceTemplate = substitutionServiceTemplate; - } + public void setSubstitutionServiceTemplate(ServiceTemplate substitutionServiceTemplate) { + this.substitutionServiceTemplate = substitutionServiceTemplate; + } - public List<UnifiedCompositionData> getUnifiedCompositionDataList() { - return unifiedCompositionDataList; - } + public List<UnifiedCompositionData> getUnifiedCompositionDataList() { + return unifiedCompositionDataList; + } - public void setUnifiedCompositionDataList( - List<UnifiedCompositionData> unifiedCompositionDataList) { - this.unifiedCompositionDataList = unifiedCompositionDataList; - } + public void setUnifiedCompositionDataList(List<UnifiedCompositionData> unifiedCompositionDataList) { + this.unifiedCompositionDataList = unifiedCompositionDataList; + } - public TranslationContext getContext() { - return context; - } + public TranslationContext getContext() { + return context; + } - public void setContext(TranslationContext context) { - this.context = context; - } + public void setContext(TranslationContext context) { + this.context = context; + } - public NodeTemplate getNodeTemplate() { - return nodeTemplate; - } + public NodeTemplate getNodeTemplate() { + return nodeTemplate; + } - public void setNodeTemplate(NodeTemplate nodeTemplate) { - this.nodeTemplate=nodeTemplate; - } + public void setNodeTemplate(NodeTemplate nodeTemplate) { + this.nodeTemplate = nodeTemplate; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java index 5e1d264f83..ddb6d52274 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.HashMap; @@ -38,19 +37,17 @@ public class ComputeConsolidationData { return fileComputeConsolidationData.get(serviceTemplateFileName); } - public void setFileComputeConsolidationData(String serviceTemplateFileName, - FileComputeConsolidationData fileComputeConsolidationData) { + public void setFileComputeConsolidationData(String serviceTemplateFileName, FileComputeConsolidationData fileComputeConsolidationData) { this.fileComputeConsolidationData.put(serviceTemplateFileName, fileComputeConsolidationData); } /** - * add compute template consolidation data entity if it doesn't exist yet - * base on given parameters. + * add compute template consolidation data entity if it doesn't exist yet base on given parameters. * * @return compute template consolidation data entity by given keys - */ - ComputeTemplateConsolidationData addComputeTemplateConsolidationData( - String serviceTemplateFileName, String computeNodeType, String computeNodeTemplateId) { + */ + ComputeTemplateConsolidationData addComputeTemplateConsolidationData(String serviceTemplateFileName, String computeNodeType, + String computeNodeTemplateId) { FileComputeConsolidationData consolidationData = addFileComputeConsolidationData(serviceTemplateFileName); return consolidationData.addComputeTemplateConsolidationData(computeNodeType, computeNodeTemplateId); } @@ -71,9 +68,7 @@ public class ComputeConsolidationData { * @return the boolean */ public boolean isNumberOfComputeTypesLegal(String serviceTemplateName) { - FileComputeConsolidationData fileComputeConsolidationData = - getFileComputeConsolidationData(serviceTemplateName); - return Objects.nonNull(fileComputeConsolidationData) - && fileComputeConsolidationData.isNumberOfComputeTypesLegal(); + FileComputeConsolidationData fileComputeConsolidationData = getFileComputeConsolidationData(serviceTemplateName); + return Objects.nonNull(fileComputeConsolidationData) && fileComputeConsolidationData.isNumberOfComputeTypesLegal(); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationDataHandler.java index 24b8524804..96324d77ba 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationDataHandler.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; +import java.util.Objects; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -28,8 +28,6 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; -import java.util.Objects; - public class ComputeConsolidationDataHandler implements ConsolidationDataHandler { private final ComputeConsolidationData computeConsolidationData; @@ -41,60 +39,45 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler @Override public void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { - String translatedSourceNodeId = translateTo.getTranslatedId(); ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, translatedSourceNodeId); String nodeType = computeNodeTemplate.getType(); - - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(translateTo, nodeType, translatedSourceNodeId); - + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(translateTo, nodeType, translatedSourceNodeId); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment); } } @Override - public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String dependentNodeTemplateId, String targetResourceId, String requirementId, - RequirementAssignment requirementAssignment) { - + public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String dependentNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, dependentNodeTemplateId); - String nodeType = getNodeType(nodeTemplate, translateTo.getHeatOrchestrationTemplate(), - targetResourceId, dependentNodeTemplateId, dependentNodeTemplateId); - - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(translateTo, nodeType, dependentNodeTemplateId); - + String nodeType = getNodeType(nodeTemplate, translateTo.getHeatOrchestrationTemplate(), targetResourceId, dependentNodeTemplateId, + dependentNodeTemplateId); + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(translateTo, nodeType, dependentNodeTemplateId); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment); } } @Override - public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, String paramName, String contrailSharedResourceId, - String sharedTranslatedResourceId) { - + public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + String paramName, String contrailSharedResourceId, String sharedTranslatedResourceId) { NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, sharedTranslatedResourceId); - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), nodeTemplate.getType(), sharedTranslatedResourceId); - + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + nodeTemplate.getType(), sharedTranslatedResourceId); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.removeParamNameFromAttrFuncList(paramName); } } @Override - public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName) { - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(functionTranslator, - functionTranslator.getResourceId(), resourceTranslatedId); - + public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName) { + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(functionTranslator, functionTranslator.getResourceId(), + resourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrOut(nodeTemplateId, getAttrFuncData); @@ -102,26 +85,21 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler } @Override - public void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId); - + public void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, + String targetResourceTranslatedId, String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(functionTranslator, targetResourceId, + targetResourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrIn(nodeTemplateId, getAttrFuncData); } - } @Override - public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId); - + public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(functionTranslator, targetResourceId, + targetResourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addOutputParamGetAttrIn(getAttrFuncData); @@ -130,33 +108,26 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler /** * Add compute in consolidation data entity base on given keys. - * */ - public void addConsolidationData(String serviceTemplateFileName, - String computeNodeType, String computeNodeTemplateId) { - getComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, computeNodeTemplateId); + public void addConsolidationData(String serviceTemplateFileName, String computeNodeType, String computeNodeTemplateId) { + getComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, computeNodeTemplateId); } /** * Add port to compute consolidation data entity base on given keys. - * */ - public void addPortToConsolidationData(TranslateTo translateTo, String computeNodeType, - String computeNodeTemplateId, String portType, String portNodeTemplateId) { - ComputeTemplateConsolidationData consolidationData = - getComputeTemplateConsolidationData(translateTo, computeNodeType, computeNodeTemplateId); + public void addPortToConsolidationData(TranslateTo translateTo, String computeNodeType, String computeNodeTemplateId, String portType, + String portNodeTemplateId) { + ComputeTemplateConsolidationData consolidationData = getComputeTemplateConsolidationData(translateTo, computeNodeType, computeNodeTemplateId); consolidationData.addPort(portType, portNodeTemplateId); } /** * Add volume to consolidation data. - * */ - public void addVolumeToConsolidationData(TranslateTo translateTo, String computeNodeType, - String computeNodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { - ComputeTemplateConsolidationData consolidationData = - getComputeTemplateConsolidationData(translateTo, computeNodeType, - computeNodeTemplateId); + public void addVolumeToConsolidationData(TranslateTo translateTo, String computeNodeType, String computeNodeTemplateId, String requirementId, + RequirementAssignment requirementAssignment) { + ComputeTemplateConsolidationData consolidationData = getComputeTemplateConsolidationData(translateTo, computeNodeType, computeNodeTemplateId); consolidationData.addVolume(requirementId, requirementAssignment); } @@ -165,12 +136,9 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler * * @param translatedGroupId Group id of which compute node is a part */ - - public void addGroupIdToConsolidationData(TranslateTo translateTo, String computeNodeType, - String computeNodeTemplateId, String translatedGroupId) { - ComputeTemplateConsolidationData consolidationData = - getComputeTemplateConsolidationData(translateTo, computeNodeType, - computeNodeTemplateId); + public void addGroupIdToConsolidationData(TranslateTo translateTo, String computeNodeType, String computeNodeTemplateId, + String translatedGroupId) { + ComputeTemplateConsolidationData consolidationData = getComputeTemplateConsolidationData(translateTo, computeNodeType, computeNodeTemplateId); consolidationData.addGroupId(translatedGroupId); } @@ -178,46 +146,41 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler return computeConsolidationData.isNumberOfComputeTypesLegal(serviceTemplateName); } - private EntityConsolidationData getComputeTemplateConsolidationData(FunctionTranslator functionTranslator, - String resourceId, String computeNodeTemplateId) { + private EntityConsolidationData getComputeTemplateConsolidationData(FunctionTranslator functionTranslator, String resourceId, + String computeNodeTemplateId) { HeatOrchestrationTemplate heatOrchestrationTemplate = functionTranslator.getHeatOrchestrationTemplate(); TranslationContext context = functionTranslator.getContext(); String heatFileName = functionTranslator.getHeatFileName(); String translatedId = context.getTranslatedIds().get(heatFileName).get(resourceId); ServiceTemplate serviceTemplate = functionTranslator.getServiceTemplate(); String computeType = getNodeType(heatOrchestrationTemplate, resourceId, resourceId, translatedId); - return getComputeTemplateConsolidationData( - ToscaUtil.getServiceTemplateFileName(serviceTemplate), computeType, computeNodeTemplateId); + return getComputeTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), computeType, computeNodeTemplateId); } - private ComputeTemplateConsolidationData getComputeTemplateConsolidationData( - TranslateTo translateTo, String computeNodeType, String computeNodeTemplateId) { + private ComputeTemplateConsolidationData getComputeTemplateConsolidationData(TranslateTo translateTo, String computeNodeType, + String computeNodeTemplateId) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); return getComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, computeNodeTemplateId); } - private ComputeTemplateConsolidationData getComputeTemplateConsolidationData( - String serviceTemplateFileName, String computeNodeType, String computeNodeTemplateId) { - - return computeConsolidationData.addComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, - computeNodeTemplateId); - + private ComputeTemplateConsolidationData getComputeTemplateConsolidationData(String serviceTemplateFileName, String computeNodeType, + String computeNodeTemplateId) { + return computeConsolidationData.addComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, computeNodeTemplateId); } - private String getNodeType(HeatOrchestrationTemplate heatOrchestrationTemplate, - String targetResourceId, String nodeTemplateId, String translatedId) { - return getNodeType(null, heatOrchestrationTemplate, targetResourceId, - nodeTemplateId, translatedId); + private String getNodeType(HeatOrchestrationTemplate heatOrchestrationTemplate, String targetResourceId, String nodeTemplateId, + String translatedId) { + return getNodeType(null, heatOrchestrationTemplate, targetResourceId, nodeTemplateId, translatedId); } - private String getNodeType(NodeTemplate computeNodeTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, - String targetResourceId, String nodeTemplateId, String translatedId) { + private String getNodeType(NodeTemplate computeNodeTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, String targetResourceId, + String nodeTemplateId, String translatedId) { if (Objects.isNull(computeNodeTemplate)) { Resource targetResource = heatOrchestrationTemplate.getResources().get(targetResourceId); NameExtractor nodeTypeNameExtractor = TranslationContext.getNameExtractorImpl(targetResource.getType()); - return nodeTypeNameExtractor.extractNodeTypeName(heatOrchestrationTemplate.getResources() - .get(nodeTemplateId), nodeTemplateId, translatedId); + return nodeTypeNameExtractor + .extractNodeTypeName(heatOrchestrationTemplate.getResources().get(nodeTemplateId), nodeTemplateId, translatedId); } return computeNodeTemplate.getType(); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java index 639bcfbfcd..9ef9032a5f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java @@ -13,29 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; - import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; public class ComputeTemplateConsolidationData extends EntityConsolidationData { // key - volume node template id + // value - List of requirement id and the requirement assignment on the + // compute node which connect to this volume private Multimap<String, RequirementAssignmentData> volumes; - // key - port type (port id excluding index), + // value - List of connected port node template ids, with this port type private Map<String, List<String>> ports; @@ -67,8 +66,7 @@ public class ComputeTemplateConsolidationData extends EntityConsolidationData { if (this.volumes == null) { this.volumes = ArrayListMultimap.create(); } - this.volumes.put(requirementAssignment.getNode(), new RequirementAssignmentData(requirementId, - requirementAssignment)); + this.volumes.put(requirementAssignment.getNode(), new RequirementAssignmentData(requirementId, requirementAssignment)); } /** @@ -92,8 +90,7 @@ public class ComputeTemplateConsolidationData extends EntityConsolidationData { */ public boolean isNumberOfPortFromEachTypeLegal() { Map<String, List<String>> currPortsMap = getPorts(); - return MapUtils.isEmpty(currPortsMap) || currPortsMap.values().stream() - .allMatch(portList -> portList.size() == 1); + return MapUtils.isEmpty(currPortsMap) || currPortsMap.values().stream().allMatch(portList -> portList.size() == 1); } public Set<String> getPortsIds() { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java index 053795b82b..9f34aa3046 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java @@ -13,37 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; -import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType; - import java.util.Optional; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType; public class ConsolidationData { private final ComputeConsolidationData computeConsolidationData; private final ComputeConsolidationDataHandler computeConsolidationDataHandler; - private final PortConsolidationData portConsolidationData; private final PortConsolidationDataHandler portConsolidationDataHandler; private final SubInterfaceConsolidationDataHandler subInterfaceConsolidationDataHandler; - - private NestedConsolidationData nestedConsolidationData; private final NestedConsolidationDataHandler nestedConsolidationDataHandler; + private NestedConsolidationData nestedConsolidationData; public ConsolidationData() { - computeConsolidationData = new ComputeConsolidationData(); computeConsolidationDataHandler = new ComputeConsolidationDataHandler(computeConsolidationData); - portConsolidationData = new PortConsolidationData(); portConsolidationDataHandler = new PortConsolidationDataHandler(portConsolidationData); subInterfaceConsolidationDataHandler = new SubInterfaceConsolidationDataHandler(portConsolidationData); - nestedConsolidationData = new NestedConsolidationData(); nestedConsolidationDataHandler = new NestedConsolidationDataHandler(nestedConsolidationData); - } /** @@ -52,7 +44,6 @@ public class ConsolidationData { * @return If there is no consolidation handler for a type, return an empty {@link Optional}. */ public Optional<ConsolidationDataHandler> getConsolidationDataHandler(ConsolidationEntityType type) { - switch (type) { case COMPUTE: return Optional.of(getComputeConsolidationDataHandler()); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationDataHandler.java index ade5fd21f3..fc945e1323 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationDataHandler.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; @@ -31,8 +30,7 @@ public interface ConsolidationDataHandler { * @param requirementId the requirement id of requirement assignment * @param requirementAssignment the requirement assignment data connected to target node */ - void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, - String requirementId, RequirementAssignment requirementAssignment); + void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment); /** * Add source node connected in to target node consolidation entity. @@ -43,22 +41,18 @@ public interface ConsolidationDataHandler { * @param requirementId the requirement id of source node * @param requirementAssignment the requirement assignment data of source node */ - void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String targetNodeTemplateId, - String targetResourceId, String requirementId, - RequirementAssignment requirementAssignment); + void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String targetNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment); - void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String paramName, String contrailSharedResourceId, - String sharedTranslatedResourceId); + void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, String paramName, + String contrailSharedResourceId, String sharedTranslatedResourceId); - void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName); + void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName); - void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, - String targetResourceId, String targetResourceTranslatedId, String propertyName, String attributeName); + void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName); - void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName); + void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java index 814011d846..ac1fa57481 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java @@ -13,12 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -27,7 +25,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; @@ -38,26 +35,24 @@ import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; public class EntityConsolidationData { private String nodeTemplateId; - //groups that point to this entity node template private List<String> groupIds; - // key - node template id which has connection to this entity + // value - List of Requirement assignment data which connect to this entity private Multimap<String, RequirementAssignmentData> nodesConnectedIn; - // key - node template id which connected from this entity + // List of Requirement assignment data which connect to the key node template id private Multimap<String, RequirementAssignmentData> nodesConnectedOut; - //key - node template id which include get attribute function from this entity + //value - List of getAttr data private Map<String, List<GetAttrFuncData>> nodesGetAttrIn; - //key - node template id which is pointed by this entity using get attribute function + //value - List of getAttr data private Map<String, List<GetAttrFuncData>> nodesGetAttrOut; - //List of getAttr data private List<GetAttrFuncData> outputParametersGetAttrIn; @@ -87,16 +82,6 @@ public class EntityConsolidationData { this.groupIds = groupIds; } - - /** - * Sets node connected to me. - * - * @param nodesConnectedIn the node connected to me - */ - public void setNodesConnectedIn(Multimap<String, RequirementAssignmentData> nodesConnectedIn) { - this.nodesConnectedIn = nodesConnectedIn; - } - /** * Add node connected to me. * @@ -104,15 +89,11 @@ public class EntityConsolidationData { * @param requirementId the requirement id * @param requirementAssignment the requirement assignment */ - public void addNodesConnectedIn(String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { - + public void addNodesConnectedIn(String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { if (this.nodesConnectedIn == null) { this.nodesConnectedIn = ArrayListMultimap.create(); } - - this.nodesConnectedIn.get(nodeTemplateId).add( - new RequirementAssignmentData(requirementId, requirementAssignment)); + this.nodesConnectedIn.get(nodeTemplateId).add(new RequirementAssignmentData(requirementId, requirementAssignment)); } /** @@ -124,6 +105,14 @@ public class EntityConsolidationData { return nodesConnectedIn; } + /** + * Sets node connected to me. + * + * @param nodesConnectedIn the node connected to me + */ + public void setNodesConnectedIn(Multimap<String, RequirementAssignmentData> nodesConnectedIn) { + this.nodesConnectedIn = nodesConnectedIn; + } /** * Gets node connected from me. @@ -150,15 +139,11 @@ public class EntityConsolidationData { * @param requirementId the requirement id * @param requirementAssignment the requirement assignment */ - public void addNodesConnectedOut(String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { - + public void addNodesConnectedOut(String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { if (this.nodesConnectedOut == null) { this.nodesConnectedOut = ArrayListMultimap.create(); } - - this.nodesConnectedOut.get(nodeTemplateId).add( - new RequirementAssignmentData(requirementId, requirementAssignment)); + this.nodesConnectedOut.get(nodeTemplateId).add(new RequirementAssignmentData(requirementId, requirementAssignment)); } /** @@ -186,11 +171,9 @@ public class EntityConsolidationData { * @param getAttrFuncData get attr data */ public void addNodesGetAttrIn(String nodeTemplateId, GetAttrFuncData getAttrFuncData) { - if (nodesGetAttrIn == null) { nodesGetAttrIn = new HashMap<>(); } - this.nodesGetAttrIn.putIfAbsent(nodeTemplateId, new ArrayList<>()); this.nodesGetAttrIn.get(nodeTemplateId).add(getAttrFuncData); } @@ -219,11 +202,9 @@ public class EntityConsolidationData { * @param getAttrFuncData get attr data */ public void addOutputParamGetAttrIn(GetAttrFuncData getAttrFuncData) { - if (outputParametersGetAttrIn == null) { outputParametersGetAttrIn = new ArrayList<>(); } - this.outputParametersGetAttrIn.add(getAttrFuncData); } @@ -252,21 +233,17 @@ public class EntityConsolidationData { * @param getAttrFuncData get attr data */ public void addNodesGetAttrOut(String nodeTemplateId, GetAttrFuncData getAttrFuncData) { - if (nodesGetAttrOut == null) { nodesGetAttrOut = new HashMap<>(); } - this.nodesGetAttrOut.putIfAbsent(nodeTemplateId, new ArrayList<>()); this.nodesGetAttrOut.get(nodeTemplateId).add(getAttrFuncData); } public void removeParamNameFromAttrFuncList(String paramName) { - if (outputParametersGetAttrIn == null) { return; } - outputParametersGetAttrIn.removeIf(outputParameters -> paramName.equals(outputParameters.getFieldName())); } @@ -275,23 +252,17 @@ public class EntityConsolidationData { * * @param entityConsolidationDataList consolidation data list * @param portTypeToIds the port type to ids - * @return true in case get attr list same for all port types. - * otherwise return false + * @return true in case get attr list same for all port types. otherwise return false */ - public boolean isGetAttrOutFromEntityLegal(Collection<? extends EntityConsolidationData> - entityConsolidationDataList, Map<String, List<String>> portTypeToIds) { - if (CollectionUtils.isEmpty(entityConsolidationDataList) - || MapUtils.isEmpty(portTypeToIds)) { + public boolean isGetAttrOutFromEntityLegal(Collection<? extends EntityConsolidationData> entityConsolidationDataList, + Map<String, List<String>> portTypeToIds) { + if (CollectionUtils.isEmpty(entityConsolidationDataList) || MapUtils.isEmpty(portTypeToIds)) { return true; } - for (String portType : portTypeToIds.keySet()) { - Set<GetAttrFuncData> startingGetAttrFunc = - getEntityGetAttrFuncAsSet(portType, portTypeToIds); - + Set<GetAttrFuncData> startingGetAttrFunc = getEntityGetAttrFuncAsSet(portType, portTypeToIds); for (EntityConsolidationData entity : entityConsolidationDataList) { - Set<GetAttrFuncData> currentGetAttrFuncData = - entity.getEntityGetAttrFuncAsSet(portType, portTypeToIds); + Set<GetAttrFuncData> currentGetAttrFuncData = entity.getEntityGetAttrFuncAsSet(portType, portTypeToIds); if (!(startingGetAttrFunc.equals(currentGetAttrFuncData))) { return false; } @@ -304,12 +275,8 @@ public class EntityConsolidationData { if (MapUtils.isEmpty(nodesGetAttrOut)) { return new HashSet<>(); } - - return nodesGetAttrOut.entrySet().stream() - .filter(entry -> portType.equals(getPortTypeFromNodeTemplateId(entry.getKey(), - portTypeToIds))) - .flatMap(entry -> entry.getValue().stream()) - .collect(Collectors.toSet()); + return nodesGetAttrOut.entrySet().stream().filter(entry -> portType.equals(getPortTypeFromNodeTemplateId(entry.getKey(), portTypeToIds))) + .flatMap(entry -> entry.getValue().stream()).collect(Collectors.toSet()); } private String getPortTypeFromNodeTemplateId(String portNodeTemplateId, Map<String, List<String>> portTypeToIds) { @@ -324,9 +291,8 @@ public class EntityConsolidationData { /** * Add group id information to consolidation data. * - * @param groupId Group id of which compute node is a part + * @param groupId Group id of which compute node is a part */ - void addGroupId(String groupId) { if (groupIds == null) { groupIds = new ArrayList<>(); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java index bde0dc0ede..daf03cd141 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Collection; @@ -42,20 +41,16 @@ public class FileComputeConsolidationData { return typeComputeConsolidationData.get(computeType); } - public void setTypeComputeConsolidationData(String computeType, TypeComputeConsolidationData - typeComputeConsolidationData) { + public void setTypeComputeConsolidationData(String computeType, TypeComputeConsolidationData typeComputeConsolidationData) { this.typeComputeConsolidationData.put(computeType, typeComputeConsolidationData); } - /** - * add compute template consolidation data according to given key if it doesn't exist yet. - * - * @return compute template consolidation data by given keys - */ - ComputeTemplateConsolidationData addComputeTemplateConsolidationData( - String computeType, String computeNodeTemplateId) { - + * add compute template consolidation data according to given key if it doesn't exist yet. + * + * @return compute template consolidation data by given keys + */ + ComputeTemplateConsolidationData addComputeTemplateConsolidationData(String computeType, String computeNodeTemplateId) { TypeComputeConsolidationData consolidationData = addTypeComputeConsolidationData(computeType); return consolidationData.addComputeTemplateConsolidationData(computeNodeTemplateId); } @@ -75,10 +70,8 @@ public class FileComputeConsolidationData { * @return the boolean */ public boolean isNumberOfComputeTypesLegal() { - Collection<TypeComputeConsolidationData> typeComputeConsolidationDataCollection = - getAllTypeComputeConsolidationData(); - return typeComputeConsolidationDataCollection.size() == 1 - && typeComputeConsolidationDataCollection.iterator().next() - .isNumberOfComputeConsolidationDataPerTypeLegal(); + Collection<TypeComputeConsolidationData> typeComputeConsolidationDataCollection = getAllTypeComputeConsolidationData(); + return typeComputeConsolidationDataCollection.size() == 1 && typeComputeConsolidationDataCollection.iterator().next() + .isNumberOfComputeConsolidationDataPerTypeLegal(); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java index 61f727ab49..2cd431a39b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Collection; @@ -38,23 +37,20 @@ public class FileNestedConsolidationData { return nestedTemplateConsolidationData.values(); } - public NestedTemplateConsolidationData getNestedTemplateConsolidationData( - String nestedNodeTemplateId) { + public NestedTemplateConsolidationData getNestedTemplateConsolidationData(String nestedNodeTemplateId) { return nestedTemplateConsolidationData.get(nestedNodeTemplateId); } - public void setNestedTemplateConsolidationData( - String nestedNodeTemplateId, - NestedTemplateConsolidationData nestedTemplateConsolidationData) { + public void setNestedTemplateConsolidationData(String nestedNodeTemplateId, NestedTemplateConsolidationData nestedTemplateConsolidationData) { this.nestedTemplateConsolidationData.put(nestedNodeTemplateId, nestedTemplateConsolidationData); } /** - * create nested template consolidation data if it doesn't exist yet. - * - * @param nestedNodeTemplateId nested node template id - * @return nested template consolidation data by given key - */ + * create nested template consolidation data if it doesn't exist yet. + * + * @param nestedNodeTemplateId nested node template id + * @return nested template consolidation data by given key + */ NestedTemplateConsolidationData addNestedTemplateConsolidationData(String nestedNodeTemplateId) { NestedTemplateConsolidationData consolidationData = getNestedTemplateConsolidationData(nestedNodeTemplateId); if (consolidationData == null) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java index 0300f9fcd9..5b6fe10ab5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Collection; @@ -45,56 +44,44 @@ public class FilePortConsolidationData { return portTemplateConsolidationData.get(portNodeTemplateId); } - public void setPortTemplateConsolidationData(String portNodeTemplateId, - PortTemplateConsolidationData - portTemplateConsolidationData) { + public void setPortTemplateConsolidationData(String portNodeTemplateId, PortTemplateConsolidationData portTemplateConsolidationData) { this.portTemplateConsolidationData.put(portNodeTemplateId, portTemplateConsolidationData); } /** - * If entity doesn't exist yet - create subInterface template consolidation data entity - * base on given parameters. - * - * @return subInterface template consolidation data entity - */ - SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - Resource resource, String subInterfaceNodeTemplateId, String parentPortNodeTemplateId) { - PortTemplateConsolidationData consolidationData = - addPortTemplateConsolidationData(parentPortNodeTemplateId); - return consolidationData.addSubInterfaceTemplateConsolidationData(resource, - subInterfaceNodeTemplateId, parentPortNodeTemplateId); + * If entity doesn't exist yet - create subInterface template consolidation data entity base on given parameters. + * + * @return subInterface template consolidation data entity + */ + SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(Resource resource, String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId) { + PortTemplateConsolidationData consolidationData = addPortTemplateConsolidationData(parentPortNodeTemplateId); + return consolidationData.addSubInterfaceTemplateConsolidationData(resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); } /** - * If entity doesn't exist yet - create subInterface template consolidation data entity - * base on given parameters. - * - * @return subInterface template consolidation data entity - */ - SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - Resource resource, String subInterfaceNodeTemplateId, String parentPortNodeTemplateId, - String parentPortResourceId, String parentPortResourceType) { - - PortTemplateConsolidationData consolidationData = - addPortTemplateConsolidationData(parentPortNodeTemplateId, parentPortResourceId, - parentPortResourceType, null); - - return consolidationData.addSubInterfaceTemplateConsolidationData(resource, - subInterfaceNodeTemplateId, parentPortNodeTemplateId); + * If entity doesn't exist yet - create subInterface template consolidation data entity base on given parameters. + * + * @return subInterface template consolidation data entity + */ + SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(Resource resource, String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId, String parentPortResourceId, + String parentPortResourceType) { + PortTemplateConsolidationData consolidationData = addPortTemplateConsolidationData(parentPortNodeTemplateId, parentPortResourceId, + parentPortResourceType, null); + return consolidationData.addSubInterfaceTemplateConsolidationData(resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); } /** - * If entity doesn't exist yet - create port template consolidation data and - * update it's network role according to given resource parameters. - * - * @return port template consolidation data entity by given keys - */ - PortTemplateConsolidationData addPortTemplateConsolidationData( - String portNodeTemplateId, String portResourceId, String portResourceType, String portType) { + * If entity doesn't exist yet - create port template consolidation data and update it's network role according to given resource parameters. + * + * @return port template consolidation data entity by given keys + */ + PortTemplateConsolidationData addPortTemplateConsolidationData(String portNodeTemplateId, String portResourceId, String portResourceType, + String portType) { PortTemplateConsolidationData consolidationData = getPortTemplateConsolidationData(portNodeTemplateId); if (consolidationData == null) { - consolidationData = createPortTemplateConsolidationData(portNodeTemplateId, - portResourceId, portResourceType, portType); + consolidationData = createPortTemplateConsolidationData(portNodeTemplateId, portResourceId, portResourceType, portType); setPortTemplateConsolidationData(portNodeTemplateId, consolidationData); } if (consolidationData.getPortType() == null) { @@ -117,14 +104,13 @@ public class FilePortConsolidationData { } return consolidationData; } - - private PortTemplateConsolidationData createPortTemplateConsolidationData(String portNodeTemplateId, - String portResourceId, String portResourceType, String portType) { + + private PortTemplateConsolidationData createPortTemplateConsolidationData(String portNodeTemplateId, String portResourceId, + String portResourceType, String portType) { PortTemplateConsolidationData consolidationData = new PortTemplateConsolidationData(); consolidationData.setNodeTemplateId(portNodeTemplateId); consolidationData.setPortType(portType); - Optional<String> portNetworkRole = HeatResourceUtil.evaluateNetworkRoleFromResourceId(portResourceId, - portResourceType); + Optional<String> portNetworkRole = HeatResourceUtil.evaluateNetworkRoleFromResourceId(portResourceId, portResourceType); portNetworkRole.ifPresent(consolidationData::setNetworkRole); return consolidationData; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java index baef222642..c60bf966b6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; /** @@ -25,58 +24,55 @@ package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolid */ public class GetAttrFuncData { - private String fieldName; - private String attributeName; - - public GetAttrFuncData(){} - - public GetAttrFuncData(String fieldName, String attributeName) { - this.fieldName = fieldName; - this.attributeName = attributeName; - } - - public String getFieldName() { - return fieldName; - } - - public void setFieldName(String fieldName) { - this.fieldName = fieldName; - } - - public String getAttributeName() { - return attributeName; - } + private String fieldName; + private String attributeName; - public void setAttributeName(String attributeName) { - this.attributeName = attributeName; - } + public GetAttrFuncData() { + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + public GetAttrFuncData(String fieldName, String attributeName) { + this.fieldName = fieldName; + this.attributeName = attributeName; } - if (o == null || getClass() != o.getClass()) { - return false; + + public String getFieldName() { + return fieldName; } - GetAttrFuncData that = (GetAttrFuncData) o; + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } - if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) { - return false; + public String getAttributeName() { + return attributeName; } - if (attributeName != null ? !attributeName.equals(that.attributeName) - : that.attributeName != null) { - return false; + + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; } - return true; - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + GetAttrFuncData that = (GetAttrFuncData) o; + if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) { + return false; + } + if (attributeName != null ? !attributeName.equals(that.attributeName) : that.attributeName != null) { + return false; + } + return true; + } - @Override - public int hashCode() { - int result = fieldName != null ? fieldName.hashCode() : 0; - result = 31 * result + (attributeName != null ? attributeName.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = fieldName != null ? fieldName.hashCode() : 0; + result = 31 * result + (attributeName != null ? attributeName.hashCode() : 0); + return result; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java index 1521d9d31e..0d24891b10 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.HashMap; @@ -38,19 +37,16 @@ public class NestedConsolidationData { return fileNestedConsolidationData.get(serviceTemplateFileName); } - public void setFileNestedConsolidationData(String serviceTemplateFileName, - FileNestedConsolidationData fileNestedConsolidationData) { + public void setFileNestedConsolidationData(String serviceTemplateFileName, FileNestedConsolidationData fileNestedConsolidationData) { this.fileNestedConsolidationData.put(serviceTemplateFileName, fileNestedConsolidationData); } /** - * Create nested template consolidation data base on given key - if it doesn't exist yet. - * - * @return nested template consolidation data by given keys - */ - NestedTemplateConsolidationData addNestedTemplateConsolidationData( - String serviceTemplateFileName, String nestedNodeTemplateId) { - + * Create nested template consolidation data base on given key - if it doesn't exist yet. + * + * @return nested template consolidation data by given keys + */ + NestedTemplateConsolidationData addNestedTemplateConsolidationData(String serviceTemplateFileName, String nestedNodeTemplateId) { FileNestedConsolidationData consolidationData = addFileNestedConsolidationData(serviceTemplateFileName); return consolidationData.addNestedTemplateConsolidationData(nestedNodeTemplateId); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationDataHandler.java index 680615000f..6643962152 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationDataHandler.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; +import java.util.Objects; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.core.utilities.file.FileUtils; @@ -27,9 +27,6 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.errors.DuplicateResourceIdsInDifferentFilesErrorBuilder; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; - -import java.util.Objects; - public class NestedConsolidationDataHandler implements ConsolidationDataHandler { private final NestedConsolidationData nestedConsolidationData; @@ -40,48 +37,35 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler @Override public void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(translateTo, translateTo.getHeatFileName(), - translateTo.getTranslatedId()); - + RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(translateTo, translateTo.getHeatFileName(), + translateTo.getTranslatedId()); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment); } } @Override - public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String dependentNodeTemplateId, String targetResourceId, - String requirementId, RequirementAssignment requirementAssignment) { - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(translateTo, translateTo.getHeatFileName(), dependentNodeTemplateId); - + public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String dependentNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(translateTo, translateTo.getHeatFileName(), + dependentNodeTemplateId); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment); } } @Override - public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String paramName, - String contrailSharedResourceId, - String sharedTranslatedResourceId) { - - throw new UnsupportedOperationException("API removeParamNameFromAttrFuncList " - + "not supported for NestedConsolidationDataHandler"); - + public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + String paramName, String contrailSharedResourceId, String sharedTranslatedResourceId) { + throw new UnsupportedOperationException("API removeParamNameFromAttrFuncList " + "not supported for NestedConsolidationDataHandler"); } @Override - public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(functionTranslator, - functionTranslator.getHeatFileName(), resourceTranslatedId); - + public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), + resourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrOut(nodeTemplateId, getAttrFuncData); @@ -89,13 +73,10 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler } @Override - public void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), - targetResourceId); - + public void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, + String targetResourceTranslatedId, String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), + targetResourceId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrIn(nodeTemplateId, getAttrFuncData); @@ -103,13 +84,10 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler } @Override - public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), - targetResourceId); - + public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), + targetResourceId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addOutputParamGetAttrIn(getAttrFuncData); @@ -119,10 +97,9 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler /** * Add nested consolidation data base on given parameters. */ - public void addConsolidationData(String serviceTemplateFileName, TranslationContext context, - String nestedHeatFileName, String nestedNodeTemplateId) { - getNestedTemplateConsolidationData(serviceTemplateFileName, context, - nestedHeatFileName, nestedNodeTemplateId); + public void addConsolidationData(String serviceTemplateFileName, TranslationContext context, String nestedHeatFileName, + String nestedNodeTemplateId) { + getNestedTemplateConsolidationData(serviceTemplateFileName, context, nestedHeatFileName, nestedNodeTemplateId); } private GetAttrFuncData createGetAttrFuncData(String propertyName, String attributeName) { @@ -132,51 +109,43 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler return getAttrFuncData; } - private NestedTemplateConsolidationData getNestedTemplateConsolidationData(FunctionTranslator functionTranslator, - String nestedHeatFileName, String nestedNodeTemplateId) { + private NestedTemplateConsolidationData getNestedTemplateConsolidationData(FunctionTranslator functionTranslator, String nestedHeatFileName, + String nestedNodeTemplateId) { ServiceTemplate serviceTemplate = functionTranslator.getServiceTemplate(); TranslationContext context = functionTranslator.getContext(); - return getNestedTemplateConsolidationData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), context, nestedHeatFileName, nestedNodeTemplateId); - + return getNestedTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), context, nestedHeatFileName, + nestedNodeTemplateId); } - private NestedTemplateConsolidationData getNestedTemplateConsolidationData(TranslateTo translateTo, - String nestedHeatFileName, String nestedNodeTemplateId) { + private NestedTemplateConsolidationData getNestedTemplateConsolidationData(TranslateTo translateTo, String nestedHeatFileName, + String nestedNodeTemplateId) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); TranslationContext context = translateTo.getContext(); - return getNestedTemplateConsolidationData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), context, nestedHeatFileName, nestedNodeTemplateId); + return getNestedTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), context, nestedHeatFileName, + nestedNodeTemplateId); } - private NestedTemplateConsolidationData getNestedTemplateConsolidationData( - String serviceTemplateFileName, TranslationContext context, - String nestedHeatFileName, String nestedNodeTemplateId) { - + private NestedTemplateConsolidationData getNestedTemplateConsolidationData(String serviceTemplateFileName, TranslationContext context, + String nestedHeatFileName, String nestedNodeTemplateId) { if (isNestedResourceIdOccursInDifferentNestedFiles(context, nestedHeatFileName, nestedNodeTemplateId)) { throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(nestedNodeTemplateId).build()); } - - if (isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates( - nestedNodeTemplateId, nestedHeatFileName, context)) { + if (isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(nestedNodeTemplateId, nestedHeatFileName, context)) { return null; } - return nestedConsolidationData - .addNestedTemplateConsolidationData(serviceTemplateFileName, nestedNodeTemplateId); + return nestedConsolidationData.addNestedTemplateConsolidationData(serviceTemplateFileName, nestedNodeTemplateId); } - private boolean isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(String nestedNodeTemplateId, - String nestedHeatFileName, TranslationContext context) { - - return context.isServiceTemplateWithoutNodeTemplatesSection( - FileUtils.getFileWithoutExtention(nestedHeatFileName)) - || context.isNodeTemplateIdPointsToStWithoutNodeTemplates(nestedNodeTemplateId); + private boolean isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(String nestedNodeTemplateId, String nestedHeatFileName, + TranslationContext context) { + return context.isServiceTemplateWithoutNodeTemplatesSection(FileUtils.getFileWithoutExtention(nestedHeatFileName)) || context + .isNodeTemplateIdPointsToStWithoutNodeTemplates(nestedNodeTemplateId); } - private boolean isNestedResourceIdOccursInDifferentNestedFiles(TranslationContext context, - String nestedHeatFileName, String nestedNodeTemplateId) { - return Objects.nonNull(nestedHeatFileName) && context.getAllTranslatedResourceIdsFromDiffNestedFiles( - nestedHeatFileName).contains(nestedNodeTemplateId); + private boolean isNestedResourceIdOccursInDifferentNestedFiles(TranslationContext context, String nestedHeatFileName, + String nestedNodeTemplateId) { + return Objects.nonNull(nestedHeatFileName) && context.getAllTranslatedResourceIdsFromDiffNestedFiles(nestedHeatFileName) + .contains(nestedNodeTemplateId); } public boolean isNestedConsolidationDataExist(String serviceTemplateName) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java index dc4ec3303f..8cd37a0fc6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; /** diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java index 132a507298..bddd45c590 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java @@ -13,14 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; -import org.openecomp.sdc.heat.datatypes.model.Resource; - import java.util.HashMap; import java.util.Map; import java.util.Set; +import org.openecomp.sdc.heat.datatypes.model.Resource; public class PortConsolidationData { @@ -39,34 +37,31 @@ public class PortConsolidationData { return filePortConsolidationData.get(serviceTemplateFileName); } - public void setFilePortConsolidationData(String serviceTemplateFileName, FilePortConsolidationData - filePortConsolidationData) { + public void setFilePortConsolidationData(String serviceTemplateFileName, FilePortConsolidationData filePortConsolidationData) { this.filePortConsolidationData.put(serviceTemplateFileName, filePortConsolidationData); } /** - * Create port template consolidation data base on given parameters - if it doesn't exist yet. - * - * @return port template consolidation data - */ - PortTemplateConsolidationData addPortTemplateConsolidationData(String serviceTemplateFileName, - String portNodeTemplateId, String portResourceId, String portResourceType, String portType) { + * Create port template consolidation data base on given parameters - if it doesn't exist yet. + * + * @return port template consolidation data + */ + PortTemplateConsolidationData addPortTemplateConsolidationData(String serviceTemplateFileName, String portNodeTemplateId, String portResourceId, + String portResourceType, String portType) { FilePortConsolidationData consolidationData = addFilePortConsolidationData(serviceTemplateFileName); - return consolidationData - .addPortTemplateConsolidationData(portNodeTemplateId, portResourceId, portResourceType, portType); + return consolidationData.addPortTemplateConsolidationData(portNodeTemplateId, portResourceId, portResourceType, portType); } /** - * Create subInterface template consolidation data base on given parameters - if it doesn't exist yet. - * - * @return port template consolidation data by given keys - */ - SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - String serviceTemplateFileName, Resource resource, String subInterfaceNodeTemplateId, - String parentPortNodeTemplateId) { + * Create subInterface template consolidation data base on given parameters - if it doesn't exist yet. + * + * @return port template consolidation data by given keys + */ + SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(String serviceTemplateFileName, Resource resource, + String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId) { FilePortConsolidationData consolidationData = addFilePortConsolidationData(serviceTemplateFileName); - return consolidationData.addSubInterfaceTemplateConsolidationData( - resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); + return consolidationData.addSubInterfaceTemplateConsolidationData(resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); } /** @@ -74,14 +69,13 @@ public class PortConsolidationData { * * @return port template consolidation data by given keys */ - SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - String serviceTemplateFileName, Resource resource, - String subInterfaceNodeTemplateId, String parentPortNodeTemplateId, - String parentPortResourceId, String parentPortResourceType) { + SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(String serviceTemplateFileName, Resource resource, + String subInterfaceNodeTemplateId, String parentPortNodeTemplateId, + String parentPortResourceId, String parentPortResourceType) { FilePortConsolidationData consolidationData = addFilePortConsolidationData(serviceTemplateFileName); - return consolidationData.addSubInterfaceTemplateConsolidationData( - resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId, - parentPortResourceId, parentPortResourceType); + return consolidationData + .addSubInterfaceTemplateConsolidationData(resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId, parentPortResourceId, + parentPortResourceType); } private FilePortConsolidationData addFilePortConsolidationData(String serviceTemplateFileName) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationDataHandler.java index 5114e5d25d..c76cec11bc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationDataHandler.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Objects; @@ -35,60 +34,43 @@ public class PortConsolidationDataHandler implements ConsolidationDataHandler { @Override public void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { - - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(translateTo, translateTo.getResourceId(), - translateTo.getResource().getType(), translateTo.getTranslatedId()); - + RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(translateTo, translateTo.getResourceId(), + translateTo.getResource().getType(), translateTo.getTranslatedId()); entityConsolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment); - } @Override - public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String dependentNodeTemplateId, String targetResourceId, String requirementId, - RequirementAssignment requirementAssignment) { - - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(translateTo, translateTo.getResourceId(), - translateTo.getResource().getType(), dependentNodeTemplateId); - + public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String dependentNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(translateTo, translateTo.getResourceId(), + translateTo.getResource().getType(), dependentNodeTemplateId); entityConsolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment); - } @Override - public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, String paramName, - String contrailSharedResourceId, String sharedTranslatedResourceId) { - + public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + String paramName, String contrailSharedResourceId, String sharedTranslatedResourceId) { Resource resource = heatOrchestrationTemplate.getResources().get(contrailSharedResourceId); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(serviceTemplateFileName, - contrailSharedResourceId, resource.getType(), sharedTranslatedResourceId, null); + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(serviceTemplateFileName, contrailSharedResourceId, + resource.getType(), sharedTranslatedResourceId, null); entityConsolidationData.removeParamNameFromAttrFuncList(paramName); - } /** * Add port in consolidation data base on given parameters. - * */ - public void addConsolidationData(String serviceTemplateFileName, - String portResourceId, String portResourceType, String portNodeTemplateId, String portType) { - getPortTemplateConsolidationData( - serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, portType); + public void addConsolidationData(String serviceTemplateFileName, String portResourceId, String portResourceType, String portNodeTemplateId, + String portType) { + getPortTemplateConsolidationData(serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, portType); } @Override - public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName) { - + public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName) { String resourceId = functionTranslator.getResourceId(); - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(functionTranslator, resourceId, resourceTranslatedId); - + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(functionTranslator, resourceId, resourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrOut(nodeTemplateId, getAttrFuncData); @@ -96,11 +78,10 @@ public class PortConsolidationDataHandler implements ConsolidationDataHandler { } @Override - public void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, - String targetResourceId, String targetResourceTranslatedId, String propertyName, String attributeName) { - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId); - + public void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, + String targetResourceTranslatedId, String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(functionTranslator, targetResourceId, + targetResourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrIn(nodeTemplateId, getAttrFuncData); @@ -108,12 +89,10 @@ public class PortConsolidationDataHandler implements ConsolidationDataHandler { } @Override - public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId); - + public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(functionTranslator, targetResourceId, + targetResourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addOutputParamGetAttrIn(getAttrFuncData); @@ -127,28 +106,25 @@ public class PortConsolidationDataHandler implements ConsolidationDataHandler { return getAttrFuncData; } - private EntityConsolidationData getPortTemplateConsolidationData(FunctionTranslator functionTranslator, - String targetResourceId, String targetResourceTranslatedId) { + private EntityConsolidationData getPortTemplateConsolidationData(FunctionTranslator functionTranslator, String targetResourceId, + String targetResourceTranslatedId) { HeatOrchestrationTemplate heatOrchestrationTemplate = functionTranslator.getHeatOrchestrationTemplate(); Resource resource = heatOrchestrationTemplate.getResources().get(targetResourceId); ServiceTemplate serviceTemplate = functionTranslator.getServiceTemplate(); - return getPortTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - targetResourceId, resource.getType(), targetResourceTranslatedId, null); + return getPortTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), targetResourceId, resource.getType(), + targetResourceTranslatedId, null); } - private PortTemplateConsolidationData getPortTemplateConsolidationData(TranslateTo translateTo, - String portResourceId, String portResourceType, String portNodeTemplateId) { + private PortTemplateConsolidationData getPortTemplateConsolidationData(TranslateTo translateTo, String portResourceId, String portResourceType, + String portNodeTemplateId) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - return getPortTemplateConsolidationData(serviceTemplateFileName, - portResourceId, portResourceType, portNodeTemplateId, null); + return getPortTemplateConsolidationData(serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, null); } - private PortTemplateConsolidationData getPortTemplateConsolidationData(String serviceTemplateFileName, - String portResourceId, String portResourceType, String portNodeTemplateId, String portType) { - - return portConsolidationData.addPortTemplateConsolidationData(serviceTemplateFileName, - portNodeTemplateId, portResourceId, portResourceType, portType); - + private PortTemplateConsolidationData getPortTemplateConsolidationData(String serviceTemplateFileName, String portResourceId, + String portResourceType, String portNodeTemplateId, String portType) { + return portConsolidationData + .addPortTemplateConsolidationData(serviceTemplateFileName, portNodeTemplateId, portResourceId, portResourceType, portType); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java index b529c7a55e..63ac262c70 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java @@ -13,31 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimaps; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - public class PortTemplateConsolidationData extends EntityConsolidationData { - // key - sub-interface type - for ResourceGroup it is the nested file name - // value - List of sub-interfaces of that type in the port - private final ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceConsolidationData = - Multimaps.synchronizedListMultimap(ArrayListMultimap.create()); + // value - List of sub-interfaces of that type in the port + private final ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceConsolidationData = Multimaps + .synchronizedListMultimap(ArrayListMultimap.create()); private String portType; - private String networkRole; public String getNetworkRole() { @@ -61,60 +57,51 @@ public class PortTemplateConsolidationData extends EntityConsolidationData { } /** - * Create Sub interface template consolidation data base on given parameters - if it doesn't exist yet. - * - * @param resource resource of sub Interface - * @param subInterfaceNodeTemplateId template id of sub interface - * @param parentPortNodeTemplateId node template id of port node to which sub interface is related - * @return sub interface template consolidation data entity - */ - public SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - Resource resource, String subInterfaceNodeTemplateId, String parentPortNodeTemplateId) { + * Create Sub interface template consolidation data base on given parameters - if it doesn't exist yet. + * + * @param resource resource of sub Interface + * @param subInterfaceNodeTemplateId template id of sub interface + * @param parentPortNodeTemplateId node template id of port node to which sub interface is related + * @return sub interface template consolidation data entity + */ + public SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(Resource resource, String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId) { String subInterfaceType = createSubInterfaceType(resource); - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - subInterfaceConsolidationData.get(subInterfaceType); + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = subInterfaceConsolidationData.get(subInterfaceType); SubInterfaceTemplateConsolidationData consolidationData = null; if (CollectionUtils.isNotEmpty(subInterfaceTemplateConsolidationDataList)) { - Optional<SubInterfaceTemplateConsolidationData> optionalConsolidationData = - subInterfaceTemplateConsolidationDataList.stream() - .filter(s -> s.getNodeTemplateId().equals(subInterfaceNodeTemplateId)) - .findFirst(); + Optional<SubInterfaceTemplateConsolidationData> optionalConsolidationData = subInterfaceTemplateConsolidationDataList.stream() + .filter(s -> s.getNodeTemplateId().equals(subInterfaceNodeTemplateId)).findFirst(); if (optionalConsolidationData.isPresent()) { consolidationData = optionalConsolidationData.get(); } } - if (Objects.isNull(consolidationData)) { - consolidationData = - createSubInterfaceConsolidationData(subInterfaceNodeTemplateId, parentPortNodeTemplateId); + consolidationData = createSubInterfaceConsolidationData(subInterfaceNodeTemplateId, parentPortNodeTemplateId); addSubInterfaceConsolidationData(subInterfaceType, consolidationData); } return consolidationData; } private String createSubInterfaceType(Resource resource) { - return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX - + FileUtils.getFileWithoutExtention( - HeatToToscaUtil.getSubInterfaceResourceType(resource)); + return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX + FileUtils + .getFileWithoutExtention(HeatToToscaUtil.getSubInterfaceResourceType(resource)); } - private SubInterfaceTemplateConsolidationData createSubInterfaceConsolidationData( - String subInterfaceNodeTemplateId, String parentPortNodeTemplateId) { + private SubInterfaceTemplateConsolidationData createSubInterfaceConsolidationData(String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId) { SubInterfaceTemplateConsolidationData data = new SubInterfaceTemplateConsolidationData(); data.setNodeTemplateId(subInterfaceNodeTemplateId); data.setParentPortNodeTemplateId(parentPortNodeTemplateId); return data; } - public void addSubInterfaceConsolidationData(String subPortType, - SubInterfaceTemplateConsolidationData - subInterfaceTemplateConsolidationData) { + public void addSubInterfaceConsolidationData(String subPortType, SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData) { this.subInterfaceConsolidationData.put(subPortType, subInterfaceTemplateConsolidationData); } public boolean hasSameSubInterfaceTypes(PortTemplateConsolidationData other) { - return other != null && this.subInterfaceConsolidationData.keySet().equals( - other.subInterfaceConsolidationData.keySet()); + return other != null && this.subInterfaceConsolidationData.keySet().equals(other.subInterfaceConsolidationData.keySet()); } public void copyMappedInto(ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceTypeToEntity) { @@ -127,31 +114,26 @@ public class PortTemplateConsolidationData extends EntityConsolidationData { public boolean isNumberOfSubInterfacesPerTypeSimilar(PortTemplateConsolidationData other) { return isBothSubInterfaceConsolidationDataEmpty(this, other) - || isBothSubInterfaceConsolidationDataNotEmpty(this, other) - && this.subInterfaceConsolidationData.keySet().stream().allMatch( - subInterfaceType -> calculateSize(other.subInterfaceConsolidationData.get(subInterfaceType)) - == calculateSize(this.subInterfaceConsolidationData.get(subInterfaceType))); - + || isBothSubInterfaceConsolidationDataNotEmpty(this, other) && this.subInterfaceConsolidationData.keySet().stream().allMatch( + subInterfaceType -> calculateSize(other.subInterfaceConsolidationData.get(subInterfaceType)) == calculateSize( + this.subInterfaceConsolidationData.get(subInterfaceType))); } - private boolean isBothSubInterfaceConsolidationDataEmpty( - PortTemplateConsolidationData object, PortTemplateConsolidationData other) { + private boolean isBothSubInterfaceConsolidationDataEmpty(PortTemplateConsolidationData object, PortTemplateConsolidationData other) { return object.subInterfaceConsolidationData.isEmpty() && other.subInterfaceConsolidationData.isEmpty(); } - private boolean isBothSubInterfaceConsolidationDataNotEmpty( - PortTemplateConsolidationData object, PortTemplateConsolidationData other) { + private boolean isBothSubInterfaceConsolidationDataNotEmpty(PortTemplateConsolidationData object, PortTemplateConsolidationData other) { return !object.subInterfaceConsolidationData.isEmpty() && !other.subInterfaceConsolidationData.isEmpty(); } public boolean isSubInterfaceNodeTemplateIdParameter(String nodeTemplateType) { - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - this.subInterfaceConsolidationData.get(nodeTemplateType); - return (Objects.nonNull(subInterfaceTemplateConsolidationDataList) - && subInterfaceTemplateConsolidationDataList.size() > 1); + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = this.subInterfaceConsolidationData + .get(nodeTemplateType); + return (Objects.nonNull(subInterfaceTemplateConsolidationDataList) && subInterfaceTemplateConsolidationDataList.size() > 1); } private int calculateSize(List<SubInterfaceTemplateConsolidationData> subInterfaces) { return subInterfaces == null ? 0 : subInterfaces.size(); } -}
\ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java index 934db78bfa..32cb7302a4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; @@ -27,54 +26,53 @@ import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; */ public class RequirementAssignmentData { - private String requirementId; - private RequirementAssignment requirementAssignment; + private String requirementId; + private RequirementAssignment requirementAssignment; - /** - * Instantiates a new Requirement assignment data. - * - * @param requirementId the requirement id - * @param requirementAssignment the requirement assignment - */ - public RequirementAssignmentData(String requirementId, RequirementAssignment - requirementAssignment) { - this.requirementId = requirementId; - this.requirementAssignment = requirementAssignment; - } + /** + * Instantiates a new Requirement assignment data. + * + * @param requirementId the requirement id + * @param requirementAssignment the requirement assignment + */ + public RequirementAssignmentData(String requirementId, RequirementAssignment requirementAssignment) { + this.requirementId = requirementId; + this.requirementAssignment = requirementAssignment; + } - /** - * Gets requirement id. - * - * @return the requirement id - */ - public String getRequirementId() { - return requirementId; - } + /** + * Gets requirement id. + * + * @return the requirement id + */ + public String getRequirementId() { + return requirementId; + } - /** - * Sets requirement id. - * - * @param requirementId the requirement id - */ - public void setRequirementId(String requirementId) { - this.requirementId = requirementId; - } + /** + * Sets requirement id. + * + * @param requirementId the requirement id + */ + public void setRequirementId(String requirementId) { + this.requirementId = requirementId; + } - /** - * Gets requirement assignment. - * - * @return the requirement assignment - */ - public RequirementAssignment getRequirementAssignment() { - return requirementAssignment; - } + /** + * Gets requirement assignment. + * + * @return the requirement assignment + */ + public RequirementAssignment getRequirementAssignment() { + return requirementAssignment; + } - /** - * Sets requirement assignment. - * - * @param requirementAssignment the requirement assignment - */ - public void setRequirementAssignment(RequirementAssignment requirementAssignment) { - this.requirementAssignment = requirementAssignment; - } + /** + * Sets requirement assignment. + * + * @param requirementAssignment the requirement assignment + */ + public void setRequirementAssignment(RequirementAssignment requirementAssignment) { + this.requirementAssignment = requirementAssignment; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceConsolidationDataHandler.java index d1b4148672..dc79cf91c9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceConsolidationDataHandler.java @@ -13,13 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -41,56 +39,42 @@ public class SubInterfaceConsolidationDataHandler implements ConsolidationDataHa @Override public void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { + RequirementAssignment requirementAssignment) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); - if (Objects.nonNull( - serviceTemplate.getTopology_template().getNode_templates().get(translateTo.getTranslatedId()))) { - Optional<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationData(translateTo, translateTo.getTranslatedId()); - - subInterfaceTemplateConsolidationData.ifPresent(consolidationData -> - consolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment)); + if (Objects.nonNull(serviceTemplate.getTopology_template().getNode_templates().get(translateTo.getTranslatedId()))) { + Optional<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationData( + translateTo, translateTo.getTranslatedId()); + subInterfaceTemplateConsolidationData + .ifPresent(consolidationData -> consolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment)); } } @Override - public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String dependentNodeTemplateId, String targetResourceId, - String requirementId, RequirementAssignment requirementAssignment) { + public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String dependentNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); TranslationContext translationContext = translateTo.getContext(); Resource targetResource = translateTo.getHeatOrchestrationTemplate().getResources().get(targetResourceId); - TranslateTo subInterfaceTo = new TranslateTo(translateTo.getHeatFileName(), serviceTemplate, - translateTo.getHeatOrchestrationTemplate(), targetResource, - targetResourceId, null, translationContext); - Optional<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationData(subInterfaceTo, targetResourceId); - - subInterfaceTemplateConsolidationData.ifPresent(consolidationData -> - consolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment)); - + TranslateTo subInterfaceTo = new TranslateTo(translateTo.getHeatFileName(), serviceTemplate, translateTo.getHeatOrchestrationTemplate(), + targetResource, targetResourceId, null, translationContext); + Optional<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationData( + subInterfaceTo, targetResourceId); + subInterfaceTemplateConsolidationData + .ifPresent(consolidationData -> consolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment)); } @Override - public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String paramName, String contrailSharedResourceId, - String sharedTranslatedResourceId) { - - - throw new UnsupportedOperationException( - "API removeParamNameFromAttrFuncList doesn't supported for SubInterfaceConsolidationDataHandler"); + public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + String paramName, String contrailSharedResourceId, String sharedTranslatedResourceId) { + throw new UnsupportedOperationException("API removeParamNameFromAttrFuncList doesn't supported for SubInterfaceConsolidationDataHandler"); } @Override - public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName) { - TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, functionTranslator.getResourceId(), - resourceTranslatedId); - - Optional<SubInterfaceTemplateConsolidationData> subInterfaceConsolidationData = - getSubInterfaceTemplateConsolidationData(subInterfaceTo, resourceTranslatedId); - + public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName) { + TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, functionTranslator.getResourceId(), resourceTranslatedId); + Optional<SubInterfaceTemplateConsolidationData> subInterfaceConsolidationData = getSubInterfaceTemplateConsolidationData(subInterfaceTo, + resourceTranslatedId); subInterfaceConsolidationData.ifPresent(consolidationData -> { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); consolidationData.addNodesGetAttrOut(nodeTemplateId, getAttrFuncData); @@ -98,15 +82,11 @@ public class SubInterfaceConsolidationDataHandler implements ConsolidationDataHa } @Override - public void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, targetResourceId, - targetResourceTranslatedId); - - Optional<SubInterfaceTemplateConsolidationData> subInterfaceConsolidationData = - getSubInterfaceTemplateConsolidationData(subInterfaceTo, targetResourceTranslatedId); - + public void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, + String targetResourceTranslatedId, String propertyName, String attributeName) { + TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, targetResourceId, targetResourceTranslatedId); + Optional<SubInterfaceTemplateConsolidationData> subInterfaceConsolidationData = getSubInterfaceTemplateConsolidationData(subInterfaceTo, + targetResourceTranslatedId); subInterfaceConsolidationData.ifPresent(consolidationData -> { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); consolidationData.addNodesGetAttrIn(nodeTemplateId, getAttrFuncData); @@ -114,14 +94,11 @@ public class SubInterfaceConsolidationDataHandler implements ConsolidationDataHa } @Override - public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, targetResourceId, - targetResourceTranslatedId); - - Optional<SubInterfaceTemplateConsolidationData> subInterfaceConsolidationData = - getSubInterfaceTemplateConsolidationData(subInterfaceTo, targetResourceTranslatedId); - + public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName) { + TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, targetResourceId, targetResourceTranslatedId); + Optional<SubInterfaceTemplateConsolidationData> subInterfaceConsolidationData = getSubInterfaceTemplateConsolidationData(subInterfaceTo, + targetResourceTranslatedId); subInterfaceConsolidationData.ifPresent(consolidationData -> { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); consolidationData.addOutputParamGetAttrIn(getAttrFuncData); @@ -129,77 +106,62 @@ public class SubInterfaceConsolidationDataHandler implements ConsolidationDataHa } public void setNetworkRole(TranslateTo translateTo, String translatedId, String networkRole) { - Optional<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationData(translateTo, translatedId); - - subInterfaceTemplateConsolidationData.ifPresent( - consolidationData -> consolidationData.setNetworkRole(networkRole)); + Optional<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationData(translateTo, + translatedId); + subInterfaceTemplateConsolidationData.ifPresent(consolidationData -> consolidationData.setNetworkRole(networkRole)); } - public void setResourceGroupCount(TranslateTo translateTo, String translatedId, - Object resourceGroupCount) { - Optional<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationData(translateTo, translatedId); - - subInterfaceTemplateConsolidationData.ifPresent( - consolidationData -> consolidationData.setResourceGroupCount(resourceGroupCount)); + public void setResourceGroupCount(TranslateTo translateTo, String translatedId, Object resourceGroupCount) { + Optional<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationData(translateTo, + translatedId); + subInterfaceTemplateConsolidationData.ifPresent(consolidationData -> consolidationData.setResourceGroupCount(resourceGroupCount)); } - private Optional<SubInterfaceTemplateConsolidationData> getSubInterfaceTemplateConsolidationData( - TranslateTo subInterfaceTo, String subInterfaceNodeTemplateId) { - Optional<String> parentPortNodeTemplateId = - HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(subInterfaceTo); - return parentPortNodeTemplateId.map(s -> getSubInterfaceTemplateConsolidationData(subInterfaceTo, - s, subInterfaceNodeTemplateId)); + private Optional<SubInterfaceTemplateConsolidationData> getSubInterfaceTemplateConsolidationData(TranslateTo subInterfaceTo, + String subInterfaceNodeTemplateId) { + Optional<String> parentPortNodeTemplateId = HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(subInterfaceTo); + return parentPortNodeTemplateId.map(s -> getSubInterfaceTemplateConsolidationData(subInterfaceTo, s, subInterfaceNodeTemplateId)); } private SubInterfaceTemplateConsolidationData getSubInterfaceTemplateConsolidationData(TranslateTo subInterfaceTo, - String parentPortNodeTemplateId, String subInterfaceNodeTemplateId) { + String parentPortNodeTemplateId, + String subInterfaceNodeTemplateId) { String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(subInterfaceTo.getServiceTemplate()); Resource resource = subInterfaceTo.getResource(); Optional<String> portResourceId = getPortResourceId(subInterfaceTo, parentPortNodeTemplateId); - if (portResourceId.isPresent()) { String portResourceType = getPortResourceType(subInterfaceTo, portResourceId.get()); return portConsolidationData - .addSubInterfaceTemplateConsolidationData(serviceTemplateFileName, resource, - subInterfaceNodeTemplateId, parentPortNodeTemplateId, - portResourceId.get(), portResourceType); + .addSubInterfaceTemplateConsolidationData(serviceTemplateFileName, resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId, + portResourceId.get(), portResourceType); } else { return portConsolidationData - .addSubInterfaceTemplateConsolidationData(serviceTemplateFileName, resource, - subInterfaceNodeTemplateId, parentPortNodeTemplateId); + .addSubInterfaceTemplateConsolidationData(serviceTemplateFileName, resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); } } private String getPortResourceType(TranslateTo subInterfaceTo, String portResourceId) { - return HeatToToscaUtil.getResourceType(portResourceId, subInterfaceTo - .getHeatOrchestrationTemplate(), subInterfaceTo.getHeatFileName()); + return HeatToToscaUtil.getResourceType(portResourceId, subInterfaceTo.getHeatOrchestrationTemplate(), subInterfaceTo.getHeatFileName()); } private Optional<String> getPortResourceId(TranslateTo subInterfaceTo, String parentPortNodeTemplateId) { - Map<String, String> resourceIdTranslatedResourceIdMap = - subInterfaceTo.getContext().getTranslatedIds().get(subInterfaceTo.getHeatFileName()); - return getSubInterfaceParentPortResourceId(parentPortNodeTemplateId, - resourceIdTranslatedResourceIdMap); + Map<String, String> resourceIdTranslatedResourceIdMap = subInterfaceTo.getContext().getTranslatedIds().get(subInterfaceTo.getHeatFileName()); + return getSubInterfaceParentPortResourceId(parentPortNodeTemplateId, resourceIdTranslatedResourceIdMap); } private Optional<String> getSubInterfaceParentPortResourceId(String parentPortNodeTemplateId, - Map<String, String> resourceIdTranslatedResourceIdMap) { + Map<String, String> resourceIdTranslatedResourceIdMap) { if (MapUtils.isEmpty(resourceIdTranslatedResourceIdMap)) { return Optional.empty(); } - return resourceIdTranslatedResourceIdMap.entrySet().stream() - .filter(entry -> entry.getValue().equals(parentPortNodeTemplateId)) - .findFirst().map(Map.Entry::getKey); + return resourceIdTranslatedResourceIdMap.entrySet().stream().filter(entry -> entry.getValue().equals(parentPortNodeTemplateId)).findFirst() + .map(Map.Entry::getKey); } - private TranslateTo createTranslateTo(FunctionTranslator functionTranslator, String resourceId, - String resourceTranslatedId) { + private TranslateTo createTranslateTo(FunctionTranslator functionTranslator, String resourceId, String resourceTranslatedId) { Resource resource = functionTranslator.getHeatOrchestrationTemplate().getResources().get(resourceId); - return new TranslateTo(ToscaUtil.getServiceTemplateFileName(functionTranslator.getServiceTemplate()), - functionTranslator.getServiceTemplate(), functionTranslator.getHeatOrchestrationTemplate(), - resource, resourceId, resourceTranslatedId, functionTranslator.getContext()); + return new TranslateTo(ToscaUtil.getServiceTemplateFileName(functionTranslator.getServiceTemplate()), functionTranslator.getServiceTemplate(), + functionTranslator.getHeatOrchestrationTemplate(), resource, resourceId, resourceTranslatedId, functionTranslator.getContext()); } private GetAttrFuncData createGetAttrFuncData(String propertyName, String attributeName) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceTemplateConsolidationData.java index 261231a5c6..a0e7c7eea2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceTemplateConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceTemplateConsolidationData.java @@ -13,68 +13,63 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; -import java.util.Optional; - public class SubInterfaceTemplateConsolidationData extends EntityConsolidationData { - //Value of the property count in the resource group representing the sub-interface - private Object resourceGroupCount; - //Network role of the sub-interface - private String networkRole; - //Parent port node template id - private String parentPortNodeTemplateId; - - public Object getResourceGroupCount() { - return resourceGroupCount; - } + //Value of the property count in the resource group representing the sub-interface + private Object resourceGroupCount; + //Network role of the sub-interface + private String networkRole; + //Parent port node template id + private String parentPortNodeTemplateId; - public void setResourceGroupCount(Object resourceGroupCount) { - this.resourceGroupCount = resourceGroupCount; - } + public Object getResourceGroupCount() { + return resourceGroupCount; + } - public String getNetworkRole() { - return networkRole; - } + public void setResourceGroupCount(Object resourceGroupCount) { + this.resourceGroupCount = resourceGroupCount; + } - public void setNetworkRole(String networkRole) { - this.networkRole = networkRole; - } + public String getNetworkRole() { + return networkRole; + } - public String getParentPortNodeTemplateId() { - return parentPortNodeTemplateId; - } + public void setNetworkRole(String networkRole) { + this.networkRole = networkRole; + } - public void setParentPortNodeTemplateId(String parentPortNodeTemplateId) { - this.parentPortNodeTemplateId = parentPortNodeTemplateId; - } + public String getParentPortNodeTemplateId() { + return parentPortNodeTemplateId; + } - public Optional<PortTemplateConsolidationData> getParentPortTemplateConsolidationData(ServiceTemplate serviceTemplate, - TranslationContext context) { - FilePortConsolidationData filePortConsolidationData = context.getConsolidationData().getPortConsolidationData() - .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); - PortTemplateConsolidationData portTemplateConsolidationData = null; - if (filePortConsolidationData != null) { - portTemplateConsolidationData = filePortConsolidationData - .getPortTemplateConsolidationData(parentPortNodeTemplateId); + public void setParentPortNodeTemplateId(String parentPortNodeTemplateId) { + this.parentPortNodeTemplateId = parentPortNodeTemplateId; } - return Optional.ofNullable(portTemplateConsolidationData); - } - public Optional<String> getParentPortNetworkRole(ServiceTemplate serviceTemplate, - TranslationContext context) { - Optional<PortTemplateConsolidationData> subInterfacePortTemplateConsolidationData = - getParentPortTemplateConsolidationData(serviceTemplate, context); - if (!subInterfacePortTemplateConsolidationData.isPresent()) { - return Optional.empty(); + public Optional<PortTemplateConsolidationData> getParentPortTemplateConsolidationData(ServiceTemplate serviceTemplate, + TranslationContext context) { + FilePortConsolidationData filePortConsolidationData = context.getConsolidationData().getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + PortTemplateConsolidationData portTemplateConsolidationData = null; + if (filePortConsolidationData != null) { + portTemplateConsolidationData = filePortConsolidationData.getPortTemplateConsolidationData(parentPortNodeTemplateId); + } + return Optional.ofNullable(portTemplateConsolidationData); } - return Optional.ofNullable(subInterfacePortTemplateConsolidationData.get().getNetworkRole()); - } + public Optional<String> getParentPortNetworkRole(ServiceTemplate serviceTemplate, TranslationContext context) { + Optional<PortTemplateConsolidationData> subInterfacePortTemplateConsolidationData = getParentPortTemplateConsolidationData(serviceTemplate, + context); + if (!subInterfacePortTemplateConsolidationData.isPresent()) { + return Optional.empty(); + } + return Optional.ofNullable(subInterfacePortTemplateConsolidationData.get().getNetworkRole()); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java index 94ea467759..8ff6140693 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java @@ -13,16 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; -import org.apache.commons.collections4.CollectionUtils; - import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.commons.collections4.CollectionUtils; public class TypeComputeConsolidationData { @@ -42,27 +40,24 @@ public class TypeComputeConsolidationData { } /** - * Gets compute template consolidation data. - * - * @param computeNodeTemplateId the compute node template id - * @return the compute template consolidation data - */ - public ComputeTemplateConsolidationData getComputeTemplateConsolidationData( - String computeNodeTemplateId) { + * Gets compute template consolidation data. + * + * @param computeNodeTemplateId the compute node template id + * @return the compute template consolidation data + */ + public ComputeTemplateConsolidationData getComputeTemplateConsolidationData(String computeNodeTemplateId) { return computeTemplateConsolidationData.get(computeNodeTemplateId); } - public void setComputeTemplateConsolidationData(String computeNodeTemplateId, - ComputeTemplateConsolidationData - computeTemplateConsolidationData) { + public void setComputeTemplateConsolidationData(String computeNodeTemplateId, ComputeTemplateConsolidationData computeTemplateConsolidationData) { this.computeTemplateConsolidationData.put(computeNodeTemplateId, computeTemplateConsolidationData); } /** - * create new compute template consolidation data if it doesn't exist yet. - * - * @return compute template consolidation data entity by given keys - */ + * create new compute template consolidation data if it doesn't exist yet. + * + * @return compute template consolidation data entity by given keys + */ ComputeTemplateConsolidationData addComputeTemplateConsolidationData(String computeNodeTemplateId) { ComputeTemplateConsolidationData consolidationData = getComputeTemplateConsolidationData(computeNodeTemplateId); if (consolidationData == null) { @@ -74,20 +69,15 @@ public class TypeComputeConsolidationData { } /** - * Gets all ports per port type, which are connected to the computes consolidation data entities - * computeTemplateConsolidationDataCollection. + * Gets all ports per port type, which are connected to the computes consolidation data entities computeTemplateConsolidationDataCollection. * * @return Map containing key as port type and value as ports id */ public Map<String, List<String>> collectAllPortsOfEachTypeFromComputes() { Map<String, List<String>> portTypeToIds = new HashMap<>(); - Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationDataCollection = - getAllComputeTemplateConsolidationData(); - + Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationDataCollection = getAllComputeTemplateConsolidationData(); computeTemplateConsolidationDataCollection - .forEach(computeTemplateConsolidationData1 -> - computeTemplateConsolidationData1.collectAllPortsOfEachTypeFromCompute(portTypeToIds)); - + .forEach(computeTemplateConsolidationData1 -> computeTemplateConsolidationData1.collectAllPortsOfEachTypeFromCompute(portTypeToIds)); return portTypeToIds; } @@ -98,13 +88,10 @@ public class TypeComputeConsolidationData { * @return true if get attr out are legal else false */ public boolean isGetAttrOutFromEntityLegal(Map<String, List<String>> portTypeToIds) { - Collection<ComputeTemplateConsolidationData> entities = getAllComputeTemplateConsolidationData(); - if (CollectionUtils.isEmpty(entities)) { return true; } - EntityConsolidationData firstEntity = entities.iterator().next(); return firstEntity.isGetAttrOutFromEntityLegal(entities, portTypeToIds); } @@ -118,23 +105,16 @@ public class TypeComputeConsolidationData { } public boolean isNumberOfPortFromEachTypeLegal() { - return getAllComputeTemplateConsolidationData().stream().allMatch( - ComputeTemplateConsolidationData::isNumberOfPortFromEachTypeLegal); + return getAllComputeTemplateConsolidationData().stream().allMatch(ComputeTemplateConsolidationData::isNumberOfPortFromEachTypeLegal); } public boolean isPortTypesEqualsBetweenComputeNodes() { Set<String> startingPortTypes = getAllComputeTemplateConsolidationData().iterator().next().getPortsIds(); - - return getAllComputeTemplateConsolidationData() - .stream().allMatch(compute -> compute.getPortsIds().equals(startingPortTypes)); + return getAllComputeTemplateConsolidationData().stream().allMatch(compute -> compute.getPortsIds().equals(startingPortTypes)); } public boolean isNumberOfPortsEqualsBetweenComputeNodes() { - int startingNumberOfPorts = - getAllComputeTemplateConsolidationData().iterator().next().getNumberOfPorts(); - - return getAllComputeTemplateConsolidationData() - .stream().allMatch(compute -> compute.getNumberOfPorts() == startingNumberOfPorts); - + int startingNumberOfPorts = getAllComputeTemplateConsolidationData().iterator().next().getNumberOfPorts(); + return getAllComputeTemplateConsolidationData().stream().allMatch(compute -> compute.getNumberOfPorts() == startingNumberOfPorts); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java index fe2286c912..8f9df4c078 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.impl.heattotosca; import org.openecomp.core.translator.api.HeatToToscaTranslator; import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory; - public class HeatToToscaTranslatorFactoryImpl extends HeatToToscaTranslatorFactory { - private static HeatToToscaTranslator INSTANCE = new HeatToToscaTranslatorImpl(); + private static HeatToToscaTranslator INSTANCE = new HeatToToscaTranslatorImpl(); - @Override - public HeatToToscaTranslator createInterface() { - return new HeatToToscaTranslatorImpl(); - } + @Override + public HeatToToscaTranslator createInterface() { + return new HeatToToscaTranslatorImpl(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java index 54a0285026..d713e9ce7c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.impl.heattotosca; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.translator.api.HeatToToscaTranslator; import org.openecomp.core.translator.datatypes.TranslatorOutput; @@ -42,102 +45,87 @@ import org.openecomp.sdc.translator.services.heattotosca.TranslationService; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionManager; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class HeatToToscaTranslatorImpl implements HeatToToscaTranslator { - private TranslationContext translationContext = new TranslationContext(); - private ValidationManager validationManager = - ValidationManagerFactory.getInstance().createInterface(); - private boolean isValid = false; - - - @Override - public void addManifest(String name, byte[] content) { - ManifestContent manifestData = JsonUtil.json2Object(new String(content), ManifestContent.class); - ManifestFile manifest = new ManifestFile(); - manifest.setName(name); - manifest.setContent(manifestData); - translationContext.setManifest(manifest); - translationContext.addFile(name, content); - validationManager.addFile(SdcCommon.MANIFEST_NAME, content); - addFilesFromManifestToTranslationContextManifestFilesMap(manifestData.getData()); - isValid = false; - } - - @Override - public void addFile(String name, byte[] content) { - translationContext.addFile(name, content); - validationManager.addFile(name, content); - isValid = false; - } - - @Override - public void addFile(String name, InputStream content) { - addFile(name, FileUtils.toByteArray(content)); - } - - - @Override - public Map<String, List<ErrorMessage>> validate() { - - Map<String, List<ErrorMessage>> errors = new HashMap<>(); - if (translationContext.getManifest() == null) { - ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.MANIFEST_NAME, errors) - .add(new ErrorMessage(ErrorLevel.ERROR, Messages.MANIFEST_NOT_EXIST.getErrorMessage())); - return errors; + private TranslationContext translationContext = new TranslationContext(); + private ValidationManager validationManager = ValidationManagerFactory.getInstance().createInterface(); + private boolean isValid = false; + + @Override + public void addManifest(String name, byte[] content) { + ManifestContent manifestData = JsonUtil.json2Object(new String(content), ManifestContent.class); + ManifestFile manifest = new ManifestFile(); + manifest.setName(name); + manifest.setContent(manifestData); + translationContext.setManifest(manifest); + translationContext.addFile(name, content); + validationManager.addFile(SdcCommon.MANIFEST_NAME, content); + addFilesFromManifestToTranslationContextManifestFilesMap(manifestData.getData()); + isValid = false; } - if (MapUtils.isEmpty(errors)) { - errors = validationManager.validate(); + @Override + public void addFile(String name, byte[] content) { + translationContext.addFile(name, content); + validationManager.addFile(name, content); + isValid = false; } - if (MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { - isValid = true; + + @Override + public void addFile(String name, InputStream content) { + addFile(name, FileUtils.toByteArray(content)); } - return errors; - } - @Override - public TranslatorOutput translate() { - TranslationService translationService = new TranslationService(); - TranslatorOutput translatorOutput = new TranslatorOutput(); - UnifiedCompositionManager unifiedCompositionManager = new UnifiedCompositionManager(new - ConsolidationService(new UnifiedCompositionService())); - if (!isValid) { - Map<String, List<ErrorMessage>> errors = validate(); + @Override + public Map<String, List<ErrorMessage>> validate() { + Map<String, List<ErrorMessage>> errors = new HashMap<>(); + if (translationContext.getManifest() == null) { + ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.MANIFEST_NAME, errors) + .add(new ErrorMessage(ErrorLevel.ERROR, Messages.MANIFEST_NOT_EXIST.getErrorMessage())); + return errors; + } + if (MapUtils.isEmpty(errors)) { + errors = validationManager.validate(); + } + if (MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { + isValid = true; + } + return errors; + } - if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { - translatorOutput.setErrorMessages(errors); + @Override + public TranslatorOutput translate() { + TranslationService translationService = new TranslationService(); + TranslatorOutput translatorOutput = new TranslatorOutput(); + UnifiedCompositionManager unifiedCompositionManager = new UnifiedCompositionManager( + new ConsolidationService(new UnifiedCompositionService())); + if (!isValid) { + Map<String, List<ErrorMessage>> errors = validate(); + if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { + translatorOutput.setErrorMessages(errors); + return translatorOutput; + } + } + translatorOutput = translationService.translateHeatFiles(translationContext); + ToscaServiceModel unifiedToscaServiceModel = unifiedCompositionManager + .createUnifiedComposition(translatorOutput.getToscaServiceModel(), translationContext); + translatorOutput.setToscaServiceModel(unifiedToscaServiceModel); return translatorOutput; - } } - translatorOutput = translationService.translateHeatFiles(translationContext); - ToscaServiceModel unifiedToscaServiceModel = unifiedCompositionManager - .createUnifiedComposition(translatorOutput.getToscaServiceModel(), translationContext); - translatorOutput.setToscaServiceModel(unifiedToscaServiceModel); - return translatorOutput; - } - - @Override - public void addExternalArtifacts(String name, byte[] content) { - translationContext.addExternalArtifacts(name, content); - } - - @Override - public void addExternalArtifacts(String name, InputStream content) { - addExternalArtifacts(name, FileUtils.toByteArray(content)); - } - - private void addFilesFromManifestToTranslationContextManifestFilesMap( - List<FileData> fileDataListFromManifest) { - for (FileData fileFromManfiest : fileDataListFromManifest) { - translationContext.addManifestFile(fileFromManfiest.getFile(), fileFromManfiest.getType()); + @Override + public void addExternalArtifacts(String name, byte[] content) { + translationContext.addExternalArtifacts(name, content); } - } + @Override + public void addExternalArtifacts(String name, InputStream content) { + addExternalArtifacts(name, FileUtils.toByteArray(content)); + } + private void addFilesFromManifestToTranslationContextManifestFilesMap(List<FileData> fileDataListFromManifest) { + for (FileData fileFromManfiest : fileDataListFromManifest) { + translationContext.addManifestFile(fileFromManfiest.getFile(), fileFromManfiest.getType()); + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java index 676eb7d7a9..69d0f186a6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java @@ -13,41 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; public class ConfigConstants { - //namespaces - public static final String MANDATORY_TRANSLATOR_NAMESPACE = "mandatoryHeatToToscaTranslator"; - public static final String MANDATORY_UNIFIED_MODEL_NAMESPACE = "mandatoryUnifiedModel"; - public static final String UNIFIED_MODEL_NAMESPACE = "unifiedModel"; - public static final String TRANSLATOR_NAMESPACE = "heatToToscaTranslator"; - public static final String MAPPING_NAMESPACE = "heatToToscaMapping"; - - //keys - public static final String RESOURCE_TRANSLATION_IMPL_KEY = "resourceTranslationImpl"; - public static final String NESTED_RESOURCE_TRANSLATION_IMPL_KEY = "NestedResource"; - public static final String DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY = "DefaultResource"; - public static final String FUNCTION_TRANSLATION_IMPL_KEY = "functionTranslationImpl"; - public static final String NAMING_CONVENTION_EXTRACTOR_IMPL_KEY = "namingConventionExtractImpl"; - public static final String UNIFIED_COMPOSITION_IMPL_KEY = "unifiedCompositionImpl"; - public static final String CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY = "ContrailComputeNodeTypeName"; - public static final String RESOURCE_MAPPING_KEY = "resourceMapping"; - public static final String SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY = - "supportedConsolidationComputeResources"; - public static final String SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY = - "supportedConsolidationPortResources"; - public static final String ENRICH_PORT_RESOURCE_PROP = - "enrichPortResourceProperties"; - public static final String UNIFIED_MODEL_IMPL_KEY = "unifiedModelImpl"; - public static final String VFC_INSTANCE_GROUP_KEY = "vfcInstanceGroup"; - public static final String FULL_EXPOSED_PROPERTIES_KEY = - "unifiedModelImpl.vfcInstanceGroup.properties.exposedProperties"; - - //others - public static final String TRANS_MAPPING_DELIMITER_CHAR = "#"; + //namespaces + public static final String MANDATORY_TRANSLATOR_NAMESPACE = "mandatoryHeatToToscaTranslator"; + public static final String MANDATORY_UNIFIED_MODEL_NAMESPACE = "mandatoryUnifiedModel"; + public static final String UNIFIED_MODEL_NAMESPACE = "unifiedModel"; + public static final String TRANSLATOR_NAMESPACE = "heatToToscaTranslator"; + public static final String MAPPING_NAMESPACE = "heatToToscaMapping"; + //keys + public static final String RESOURCE_TRANSLATION_IMPL_KEY = "resourceTranslationImpl"; + public static final String NESTED_RESOURCE_TRANSLATION_IMPL_KEY = "NestedResource"; + public static final String DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY = "DefaultResource"; + public static final String FUNCTION_TRANSLATION_IMPL_KEY = "functionTranslationImpl"; + public static final String NAMING_CONVENTION_EXTRACTOR_IMPL_KEY = "namingConventionExtractImpl"; + public static final String UNIFIED_COMPOSITION_IMPL_KEY = "unifiedCompositionImpl"; + public static final String CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY = "ContrailComputeNodeTypeName"; + public static final String RESOURCE_MAPPING_KEY = "resourceMapping"; + public static final String SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY = "supportedConsolidationComputeResources"; + public static final String SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY = "supportedConsolidationPortResources"; + public static final String ENRICH_PORT_RESOURCE_PROP = "enrichPortResourceProperties"; + public static final String UNIFIED_MODEL_IMPL_KEY = "unifiedModelImpl"; + public static final String VFC_INSTANCE_GROUP_KEY = "vfcInstanceGroup"; + public static final String FULL_EXPOSED_PROPERTIES_KEY = "unifiedModelImpl.vfcInstanceGroup.properties.exposedProperties"; + //others + public static final String TRANS_MAPPING_DELIMITER_CHAR = "#"; - private ConfigConstants() { - } + private ConfigConstants() { + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java index 0fb2eb8606..c5ec622756 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; +import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR; + import java.util.List; import java.util.Map; import java.util.Optional; - import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; @@ -38,12 +38,10 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationDataHandler; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; -import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR; - - /** - * Utility class for consolidation data collection helper methods. - */ - public class ConsolidationDataUtil { +/** + * Utility class for consolidation data collection helper methods. + */ +public class ConsolidationDataUtil { private static final String UNDERSCORE = "_"; private static final String DIGIT_REGEX = "\\d+"; @@ -52,11 +50,10 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. // prevent instantiation of utility class } - public static boolean isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates( - String nestedNodeTemplateId, String nestedHeatFileName, TranslationContext context) { - return context.isServiceTemplateWithoutNodeTemplatesSection( - FileUtils.getFileWithoutExtention(nestedHeatFileName)) - || context.isNodeTemplateIdPointsToStWithoutNodeTemplates(nestedNodeTemplateId); + public static boolean isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(String nestedNodeTemplateId, String nestedHeatFileName, + TranslationContext context) { + return context.isServiceTemplateWithoutNodeTemplatesSection(FileUtils.getFileWithoutExtention(nestedHeatFileName)) || context + .isNodeTemplateIdPointsToStWithoutNodeTemplates(nestedNodeTemplateId); } /** @@ -67,15 +64,10 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param computeNodeTemplateId Node template id of the compute node * @param requirementAssignment RequirementAssignment object */ - public static void updateComputeConsolidationDataVolumes(TranslateTo translateTo, - String computeType, - String computeNodeTemplateId, - String requirementId, - RequirementAssignment requirementAssignment) { - ComputeConsolidationDataHandler handler = - translateTo.getContext().getComputeConsolidationDataHandler(); - handler.addVolumeToConsolidationData( - translateTo, computeType, computeNodeTemplateId, requirementId, requirementAssignment); + public static void updateComputeConsolidationDataVolumes(TranslateTo translateTo, String computeType, String computeNodeTemplateId, + String requirementId, RequirementAssignment requirementAssignment) { + ComputeConsolidationDataHandler handler = translateTo.getContext().getComputeConsolidationDataHandler(); + handler.addVolumeToConsolidationData(translateTo, computeType, computeNodeTemplateId, requirementId, requirementAssignment); } /** @@ -86,22 +78,17 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param portResourceId the port resource id * @param portNodeTemplateId the port node template id */ - public static void updatePortInConsolidationData(TranslateTo translateTo, - String computeNodeType, - String portResourceId, - String portResourceType, - String portNodeTemplateId) { + public static void updatePortInConsolidationData(TranslateTo translateTo, String computeNodeType, String portResourceId, String portResourceType, + String portNodeTemplateId) { TranslationContext translationContext = translateTo.getContext(); String computeNodeTemplateId = translateTo.getTranslatedId(); String portType = getPortType(portNodeTemplateId, DataModelUtil.getNamespaceSuffix(computeNodeType)); - - translationContext.getComputeConsolidationDataHandler().addPortToConsolidationData( - translateTo, computeNodeType, computeNodeTemplateId, portType, portNodeTemplateId); - + translationContext.getComputeConsolidationDataHandler() + .addPortToConsolidationData(translateTo, computeNodeType, computeNodeTemplateId, portType, portNodeTemplateId); ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - translationContext.getPortConsolidationDataHandler().addConsolidationData( - serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, portType); + translationContext.getPortConsolidationDataHandler() + .addConsolidationData(serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, portType); } /** @@ -112,31 +99,28 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param nodeTemplateId the source node template id * @param requirementAssignment the requirement assignment */ - public static void updateNodesConnectedData(TranslateTo translateTo, String targetResourceId, - Resource targetResource, Resource sourceResource, - String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { + public static void updateNodesConnectedData(TranslateTo translateTo, String targetResourceId, Resource targetResource, Resource sourceResource, + String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { ConsolidationEntityType consolidationEntityType = ConsolidationEntityType.OTHER; consolidationEntityType.setEntityType(sourceResource, targetResource, translateTo.getContext()); // Add resource dependency information in nodesConnectedIn if the target node + // is a consolidation entity if (isConsolidationEntity(consolidationEntityType.getTargetEntityType())) { - ConsolidationDataUtil.updateNodesConnectedIn(translateTo, - nodeTemplateId, consolidationEntityType.getTargetEntityType(), targetResourceId, - requirementId, requirementAssignment); + ConsolidationDataUtil + .updateNodesConnectedIn(translateTo, nodeTemplateId, consolidationEntityType.getTargetEntityType(), targetResourceId, requirementId, + requirementAssignment); } - //Add resource dependency information in nodesConnectedOut if the source node + //is a consolidation entity if (isConsolidationEntity(consolidationEntityType.getSourceEntityType())) { - ConsolidationDataUtil.updateNodesConnectedOut(translateTo, - requirementAssignment.getNode(), consolidationEntityType.getSourceEntityType(), - requirementId, requirementAssignment); - + ConsolidationDataUtil + .updateNodesConnectedOut(translateTo, requirementAssignment.getNode(), consolidationEntityType.getSourceEntityType(), requirementId, + requirementAssignment); } } - private static boolean isConsolidationEntity(ConsolidationEntityType consolidationEntityType) { return ConsolidationEntityType.getSupportedConsolidationEntities().contains(consolidationEntityType); } @@ -150,21 +134,15 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param requirementId the requirement id * @param requirementAssignment the requirement assignment */ - public static void updateNodesConnectedOut(TranslateTo translateTo, - String nodeTemplateId, - ConsolidationEntityType consolidationEntityType, - String requirementId, - RequirementAssignment requirementAssignment) { + public static void updateNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, ConsolidationEntityType consolidationEntityType, + String requirementId, RequirementAssignment requirementAssignment) { TranslationContext translationContext = translateTo.getContext(); - translationContext.updateRequirementAssignmentIdIndex( - ToscaUtil.getServiceTemplateFileName(translateTo.getServiceTemplate()), translateTo.getResourceId(), + translationContext + .updateRequirementAssignmentIdIndex(ToscaUtil.getServiceTemplateFileName(translateTo.getServiceTemplate()), translateTo.getResourceId(), requirementId); - - Optional<ConsolidationDataHandler> consolidationDataHandler = - translationContext.getConsolidationDataHandler(consolidationEntityType); - consolidationDataHandler.ifPresent(handler -> handler.addNodesConnectedOut( - translateTo, nodeTemplateId, requirementId, requirementAssignment)); - + Optional<ConsolidationDataHandler> consolidationDataHandler = translationContext.getConsolidationDataHandler(consolidationEntityType); + consolidationDataHandler + .ifPresent(handler -> handler.addNodesConnectedOut(translateTo, nodeTemplateId, requirementId, requirementAssignment)); } /** @@ -177,20 +155,13 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param requirementId Requirement Id * @param requirementAssignment the requirement assignment */ - public static void updateNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - ConsolidationEntityType consolidationEntityType, - String targetResourceId, - String requirementId, - RequirementAssignment requirementAssignment) { - + public static void updateNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, ConsolidationEntityType consolidationEntityType, + String targetResourceId, String requirementId, RequirementAssignment requirementAssignment) { TranslationContext translationContext = translateTo.getContext(); - Optional<ConsolidationDataHandler> consolidationDataHandler = - translationContext.getConsolidationDataHandler(consolidationEntityType); + Optional<ConsolidationDataHandler> consolidationDataHandler = translationContext.getConsolidationDataHandler(consolidationEntityType); String dependentNodeTemplateId = requirementAssignment.getNode(); - consolidationDataHandler.ifPresent( - handler -> handler.addNodesConnectedIn(translateTo, sourceNodeTemplateId, dependentNodeTemplateId, - targetResourceId, requirementId, requirementAssignment)); - + consolidationDataHandler.ifPresent(handler -> handler + .addNodesConnectedIn(translateTo, sourceNodeTemplateId, dependentNodeTemplateId, targetResourceId, requirementId, requirementAssignment)); } /** @@ -201,8 +172,7 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. */ public static boolean isComputeResource(Resource resource) { String resourceType = resource.getType(); - Map<String, ImplementationConfiguration> supportedComputeResources = - TranslationContext.getSupportedConsolidationComputeResources(); + Map<String, ImplementationConfiguration> supportedComputeResources = TranslationContext.getSupportedConsolidationComputeResources(); if (supportedComputeResources.containsKey(resourceType)) { return supportedComputeResources.get(resourceType).isEnable(); } @@ -217,8 +187,7 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. */ public static boolean isPortResource(Resource resource) { String resourceType = resource.getType(); - Map<String, ImplementationConfiguration> supportedPortResources = - TranslationContext.getSupportedConsolidationPortResources(); + Map<String, ImplementationConfiguration> supportedPortResources = TranslationContext.getSupportedConsolidationPortResources(); if (supportedPortResources.containsKey(resourceType)) { return supportedPortResources.get(resourceType).isEnable(); } @@ -233,9 +202,8 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. */ public static boolean isVolumeResource(Resource resource) { String resourceType = resource.getType(); - return resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()) - || resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE - .getHeatResource()); + return resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()) || resourceType + .equals(HeatResourcesTypes.CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE.getHeatResource()); } /** @@ -245,32 +213,26 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @return the port type */ public static String getPortType(String portNodeTemplateId, String vmType) { - if (StringUtils.isBlank(portNodeTemplateId) || !portNodeTemplateId.startsWith(vmType + UNDERSCORE)) { return portNodeTemplateId; } String temp = portNodeTemplateId.substring(portNodeTemplateId.indexOf(vmType) + vmType.length()); - StringBuilder sb = new StringBuilder(vmType + UNDERSCORE); String[] tokens = temp.split(UNDERSCORE); - if (tokens.length == 0) { return portNodeTemplateId; } - - for (int i=0; i<tokens.length; i++) { + for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; if (token.matches(DIGIT_REGEX) && i != 1) { sb.append(token); sb.append(UNDERSCORE); } - if (StringUtils.isNotBlank(token) && !token.matches(DIGIT_REGEX)) { sb.append(token); sb.append(UNDERSCORE); } } - return portNodeTemplateId.endsWith(UNDERSCORE) ? sb.toString() : sb.substring(0, sb.length() - 1); } @@ -285,73 +247,57 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); // create nested in consolidation data context.getNestedConsolidationDataHandler() - .addConsolidationData(serviceTemplateFileName, context, - translateTo.getHeatFileName(), translateTo.getTranslatedId()); - + .addConsolidationData(serviceTemplateFileName, context, translateTo.getHeatFileName(), translateTo.getTranslatedId()); } - public static void removeSharedResource(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context, - String paramName, - String contrailSharedResourceId, - String sharedTranslatedResourceId) { - Optional<ConsolidationDataHandler> consolidationDataHandler = - ConsolidationDataUtil.getConsolidationDataHandler(heatOrchestrationTemplate, context, - contrailSharedResourceId); - - consolidationDataHandler.ifPresent( - handler -> handler.removeParamNameFromAttrFuncList(serviceTemplate, heatOrchestrationTemplate, - paramName, contrailSharedResourceId, sharedTranslatedResourceId)); + public static void removeSharedResource(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, String paramName, String contrailSharedResourceId, + String sharedTranslatedResourceId) { + Optional<ConsolidationDataHandler> consolidationDataHandler = ConsolidationDataUtil + .getConsolidationDataHandler(heatOrchestrationTemplate, context, contrailSharedResourceId); + consolidationDataHandler.ifPresent(handler -> handler + .removeParamNameFromAttrFuncList(serviceTemplate, heatOrchestrationTemplate, paramName, contrailSharedResourceId, + sharedTranslatedResourceId)); } - public static void updateNodeGetAttributeIn(FunctionTranslator functionTranslator, String resourceTranslatedId, - String targetResourceId, String targetResourceTranslatedId, String attributeName) { - + public static void updateNodeGetAttributeIn(FunctionTranslator functionTranslator, String resourceTranslatedId, String targetResourceId, + String targetResourceTranslatedId, String attributeName) { if (functionTranslator == null || functionTranslator.getServiceTemplate() == null) { return; } - Optional<ConsolidationDataHandler> consolidationDataHandler = - ConsolidationDataUtil.getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), - functionTranslator.getContext(), targetResourceId); - - consolidationDataHandler.ifPresent(handler -> handler.addNodesGetAttrIn(functionTranslator, - resourceTranslatedId, targetResourceId, targetResourceTranslatedId, + Optional<ConsolidationDataHandler> consolidationDataHandler = ConsolidationDataUtil + .getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext(), targetResourceId); + consolidationDataHandler.ifPresent(handler -> handler + .addNodesGetAttrIn(functionTranslator, resourceTranslatedId, targetResourceId, targetResourceTranslatedId, getToscaPropertyName(functionTranslator), attributeName)); } - public static void updateNodeGetAttributeOut(FunctionTranslator functionTranslator, - String targetTranslatedResourceId, String resourceTranslatedId, String attrName) { - + public static void updateNodeGetAttributeOut(FunctionTranslator functionTranslator, String targetTranslatedResourceId, + String resourceTranslatedId, String attrName) { if (functionTranslator == null || functionTranslator.getServiceTemplate() == null) { return; } - - Optional<ConsolidationDataHandler> consolidationDataHandler = - ConsolidationDataUtil.getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), - functionTranslator.getContext(), functionTranslator.getResourceId()); - - consolidationDataHandler.ifPresent(handler -> handler.addNodesGetAttrOut(functionTranslator, - targetTranslatedResourceId, resourceTranslatedId, getToscaPropertyName(functionTranslator), attrName)); + Optional<ConsolidationDataHandler> consolidationDataHandler = ConsolidationDataUtil + .getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext(), + functionTranslator.getResourceId()); + consolidationDataHandler.ifPresent(handler -> handler + .addNodesGetAttrOut(functionTranslator, targetTranslatedResourceId, resourceTranslatedId, getToscaPropertyName(functionTranslator), + attrName)); } - public static void updateOutputParamGetAttrIn(FunctionTranslator functionTranslator, - String targetResourceId, String targetResourceTranslatedId, String propertyName, String attrName) { + public static void updateOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attrName) { if (functionTranslator == null || functionTranslator.getServiceTemplate() == null) { return; } - - Optional<ConsolidationDataHandler> consolidationDataHandler = - ConsolidationDataUtil.getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), - functionTranslator.getContext(), targetResourceId); - - consolidationDataHandler.ifPresent(handler -> handler.addOutputParamGetAttrIn(functionTranslator, - targetResourceId, targetResourceTranslatedId, propertyName, attrName)); + Optional<ConsolidationDataHandler> consolidationDataHandler = ConsolidationDataUtil + .getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext(), targetResourceId); + consolidationDataHandler.ifPresent( + handler -> handler.addOutputParamGetAttrIn(functionTranslator, targetResourceId, targetResourceTranslatedId, propertyName, attrName)); } - private static Optional<ConsolidationDataHandler> getConsolidationDataHandler( - HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context, - String contrailSharedResourceId) { + private static Optional<ConsolidationDataHandler> getConsolidationDataHandler(HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, String contrailSharedResourceId) { Resource resource = heatOrchestrationTemplate.getResources().get(contrailSharedResourceId); ConsolidationEntityType consolidationEntityType = ConsolidationEntityType.OTHER; consolidationEntityType.setEntityType(resource, resource, context); @@ -363,8 +309,7 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. Resource resource = heatOrchestrationTemplate.getResources().get(functionTranslator.getResourceId()); String toscaPropertyName = functionTranslator.getPropertyName(); if (!HeatToToscaUtil.isNestedResource(resource)) { - return HeatToToscaUtil.getToscaPropertyName(functionTranslator.getContext(), - resource.getType(), getHeatPropertyName(toscaPropertyName)); + return HeatToToscaUtil.getToscaPropertyName(functionTranslator.getContext(), resource.getType(), getHeatPropertyName(toscaPropertyName)); } return toscaPropertyName; } @@ -376,12 +321,10 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. return toscaPropertyName; } - public static boolean isComputeReferenceToPortId(ComputeTemplateConsolidationData compute, - String portId) { + public static boolean isComputeReferenceToPortId(ComputeTemplateConsolidationData compute, String portId) { if (MapUtils.isEmpty(compute.getPorts())) { return false; } - for (List<String> portIdsPerType : compute.getPorts().values()) { if (portIdsPerType.contains(portId)) { return true; @@ -389,5 +332,4 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. } return false; } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java index f124d0474e..2e3b8386ff 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.isComputeResource; +import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.isPortResource; +import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.isVolumeResource; import java.util.Collections; import java.util.EnumSet; import java.util.Set; import java.util.stream.Collectors; - -import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.*; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; /** * The enum Entity type. @@ -32,12 +32,23 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDat public enum ConsolidationEntityType { COMPUTE, PORT, VOLUME, NESTED, //Simple nested VFC (nested file with one compute) or a complex VFC (nested ST with more than + //one compute) VFC_NESTED, SUB_INTERFACE, OTHER; - + private static final Set<ConsolidationEntityType> consolidationEntityTypes = initConsolidationEntities(); private ConsolidationEntityType sourceEntityType; private ConsolidationEntityType targetEntityType; + private static Set<ConsolidationEntityType> initConsolidationEntities() { + return Collections.unmodifiableSet(EnumSet.allOf(ConsolidationEntityType.class).stream().filter( + consolidationEntityType -> consolidationEntityType != ConsolidationEntityType.OTHER + && consolidationEntityType != ConsolidationEntityType.VOLUME).collect(Collectors.toSet())); + } + + public static Set<ConsolidationEntityType> getSupportedConsolidationEntities() { + return consolidationEntityTypes; + } + public ConsolidationEntityType getSourceEntityType() { return sourceEntityType; } @@ -46,7 +57,6 @@ public enum ConsolidationEntityType { return targetEntityType; } - /** * Sets entity type. * @@ -58,18 +68,6 @@ public enum ConsolidationEntityType { sourceEntityType = getEntityType(sourceResource, context); } - private static final Set<ConsolidationEntityType> consolidationEntityTypes = initConsolidationEntities(); - - private static Set<ConsolidationEntityType> initConsolidationEntities() { - return Collections.unmodifiableSet(EnumSet.allOf(ConsolidationEntityType.class).stream().filter( - consolidationEntityType -> consolidationEntityType != ConsolidationEntityType.OTHER - && consolidationEntityType != ConsolidationEntityType.VOLUME).collect(Collectors.toSet())); - } - - public static Set<ConsolidationEntityType> getSupportedConsolidationEntities() { - return consolidationEntityTypes; - } - private ConsolidationEntityType getEntityType(Resource resource, TranslationContext context) { ConsolidationEntityType consolidationEntityType = ConsolidationEntityType.OTHER; if (isComputeResource(resource)) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java index b99bcf8bb8..767bcd37e0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java @@ -13,13 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimap; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -33,7 +31,6 @@ import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; @@ -68,465 +65,325 @@ import org.openecomp.sdc.translator.services.heattotosca.errors.DuplicateResourc public class ConsolidationService { - private UnifiedCompositionService unifiedCompositionService; - - public ConsolidationService(UnifiedCompositionService unifiedCompositionService) { - this.unifiedCompositionService = unifiedCompositionService; - } - - ConsolidationService() { - - } + private UnifiedCompositionService unifiedCompositionService; - void serviceTemplateConsolidation(ServiceTemplate serviceTemplate, - TranslationContext translationContext) { - - ConsolidationData consolidationData = translationContext.getConsolidationData(); + public ConsolidationService(UnifiedCompositionService unifiedCompositionService) { + this.unifiedCompositionService = unifiedCompositionService; + } - FileComputeConsolidationData fileComputeConsolidationData = - consolidationData.getComputeConsolidationData() - .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + ConsolidationService() { + } - if (Objects.isNull(fileComputeConsolidationData)) { - return; - } - for (TypeComputeConsolidationData typeComputeConsolidationData : - fileComputeConsolidationData.getAllTypeComputeConsolidationData()) { - boolean preConditionResult = - consolidationPreCondition( - serviceTemplate, consolidationData, typeComputeConsolidationData); - - List<UnifiedCompositionData> unifiedCompositionDataList = - createUnifiedCompositionDataList( - serviceTemplate, consolidationData, typeComputeConsolidationData); - - if (preConditionResult) { - boolean consolidationRuleCheckResult = - checkConsolidationRules(serviceTemplate, typeComputeConsolidationData, - consolidationData); - - unifiedCompositionService.createUnifiedComposition( - serviceTemplate, null, unifiedCompositionDataList, - consolidationRuleCheckResult ? UnifiedCompositionMode.ScalingInstances - : UnifiedCompositionMode.CatalogInstance, - translationContext); - } else { - unifiedCompositionService.createUnifiedComposition( - serviceTemplate, null, unifiedCompositionDataList, UnifiedCompositionMode - .SingleSubstitution, - translationContext); - } - } - - } - - static Map<String, String> getConsolidationEntityIdToType(ServiceTemplate serviceTemplate, - ConsolidationData consolidationData) { - Map<String, String> consolidationEntityIdToType = new HashMap<>(); - - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - FileComputeConsolidationData fileComputeConsolidationData = - consolidationData.getComputeConsolidationData() + static Map<String, String> getConsolidationEntityIdToType(ServiceTemplate serviceTemplate, ConsolidationData consolidationData) { + Map<String, String> consolidationEntityIdToType = new HashMap<>(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + FileComputeConsolidationData fileComputeConsolidationData = consolidationData.getComputeConsolidationData() .getFileComputeConsolidationData(serviceTemplateFileName); - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData() + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() .getFilePortConsolidationData(serviceTemplateFileName); - if (Objects.nonNull(fileComputeConsolidationData)) { - for (String computeType : fileComputeConsolidationData.getAllComputeTypes()) { - TypeComputeConsolidationData typeComputeConsolidationData = - fileComputeConsolidationData.getTypeComputeConsolidationData(computeType); - Collection<String> computeNodeTemplateIds = - typeComputeConsolidationData.getAllComputeNodeTemplateIds(); - for (String computeNodeTemplateId : computeNodeTemplateIds) { - consolidationEntityIdToType.put(computeNodeTemplateId, computeType); + if (Objects.nonNull(fileComputeConsolidationData)) { + for (String computeType : fileComputeConsolidationData.getAllComputeTypes()) { + TypeComputeConsolidationData typeComputeConsolidationData = fileComputeConsolidationData.getTypeComputeConsolidationData(computeType); + Collection<String> computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + for (String computeNodeTemplateId : computeNodeTemplateIds) { + consolidationEntityIdToType.put(computeNodeTemplateId, computeType); + } + } + } + if (Objects.nonNull(filePortConsolidationData)) { + Set<String> portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); + for (String portNodeTemplateId : portNodeTemplateIds) { + consolidationEntityIdToType + .put(portNodeTemplateId, filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId).getPortType()); + } } - } + return consolidationEntityIdToType; } - if (Objects.nonNull(filePortConsolidationData)) { - Set<String> portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); - for (String portNodeTemplateId : portNodeTemplateIds) { - consolidationEntityIdToType - .put(portNodeTemplateId, - filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId).getPortType()); - } + void serviceTemplateConsolidation(ServiceTemplate serviceTemplate, TranslationContext translationContext) { + ConsolidationData consolidationData = translationContext.getConsolidationData(); + FileComputeConsolidationData fileComputeConsolidationData = consolidationData.getComputeConsolidationData() + .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + if (Objects.isNull(fileComputeConsolidationData)) { + return; + } + for (TypeComputeConsolidationData typeComputeConsolidationData : fileComputeConsolidationData.getAllTypeComputeConsolidationData()) { + boolean preConditionResult = consolidationPreCondition(serviceTemplate, consolidationData, typeComputeConsolidationData); + List<UnifiedCompositionData> unifiedCompositionDataList = createUnifiedCompositionDataList(serviceTemplate, consolidationData, + typeComputeConsolidationData); + if (preConditionResult) { + boolean consolidationRuleCheckResult = checkConsolidationRules(serviceTemplate, typeComputeConsolidationData, consolidationData); + unifiedCompositionService.createUnifiedComposition(serviceTemplate, null, unifiedCompositionDataList, + consolidationRuleCheckResult ? UnifiedCompositionMode.ScalingInstances : UnifiedCompositionMode.CatalogInstance, + translationContext); + } else { + unifiedCompositionService + .createUnifiedComposition(serviceTemplate, null, unifiedCompositionDataList, UnifiedCompositionMode.SingleSubstitution, + translationContext); + } + } } - return consolidationEntityIdToType; - } - - - private boolean checkConsolidationRules(ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - return checkComputeConsolidation(serviceTemplate, typeComputeConsolidationData) - && checkPortConsolidation(serviceTemplate, typeComputeConsolidationData, - consolidationData) - && !checkGetAttrBetweenEntityConsolidationOfTheSameType(serviceTemplate, - typeComputeConsolidationData, consolidationData); - } + private boolean checkConsolidationRules(ServiceTemplate serviceTemplate, TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + return checkComputeConsolidation(serviceTemplate, typeComputeConsolidationData) && checkPortConsolidation(serviceTemplate, + typeComputeConsolidationData, consolidationData) && !checkGetAttrBetweenEntityConsolidationOfTheSameType(serviceTemplate, + typeComputeConsolidationData, consolidationData); + } - private boolean checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType( - ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { + private boolean checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType(ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { Collection<String> computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); - - Map<String, List<String>> portTypeToIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); - - return typeComputeConsolidationData.isGetAttrOutFromEntityLegal(portTypeToIds) - && checkGetAttrOutFromPortLegal( - ToscaUtil.getServiceTemplateFileName(serviceTemplate), - computeNodeTemplateIds, portTypeToIds, consolidationData); - + Map<String, List<String>> portTypeToIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + return typeComputeConsolidationData.isGetAttrOutFromEntityLegal(portTypeToIds) && checkGetAttrOutFromPortLegal( + ToscaUtil.getServiceTemplateFileName(serviceTemplate), computeNodeTemplateIds, portTypeToIds, consolidationData); + } + + private boolean checkGetAttrOutFromPortLegal(String serviceTemplateName, Collection<String> computeNodeTemplateIds, + Map<String, List<String>> portTypeToIds, ConsolidationData consolidationData) { + for (List<String> portIdsFromSameType : portTypeToIds.values()) { + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = collectAllPortsTemplateConsolidationData(portIdsFromSameType, + serviceTemplateName, consolidationData); + if (!(checkGetAttrOutFromEntityToPortIsLegal(portTemplateConsolidationDataList, portTypeToIds) + && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal(portTemplateConsolidationDataList, computeNodeTemplateIds))) { + return false; + } + } + return true; } - private boolean checkGetAttrOutFromPortLegal(String serviceTemplateName, - Collection<String> computeNodeTemplateIds, - Map<String, List<String>> portTypeToIds, - ConsolidationData consolidationData) { - for (List<String> portIdsFromSameType : portTypeToIds.values()) { - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - collectAllPortsTemplateConsolidationData(portIdsFromSameType, serviceTemplateName, - consolidationData); - - if (!(checkGetAttrOutFromEntityToPortIsLegal(portTemplateConsolidationDataList, portTypeToIds) - && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( - portTemplateConsolidationDataList, - computeNodeTemplateIds))) { - return false; - } + private boolean checkGetAttrOutFromEntityToPortIsLegal(Collection<? extends EntityConsolidationData> entities, + Map<String, List<String>> portTypeToIds) { + return CollectionUtils.isEmpty(entities) || entities.iterator().next().isGetAttrOutFromEntityLegal(entities, portTypeToIds); } - return true; - } - - private boolean checkGetAttrOutFromEntityToPortIsLegal(Collection<? extends EntityConsolidationData> entities, - Map<String, List<String>> portTypeToIds) { - return CollectionUtils.isEmpty(entities) - || entities.iterator().next().isGetAttrOutFromEntityLegal(entities, portTypeToIds); - } - - private boolean checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( - List entityConsolidationDataList, - Collection<String> consolidationEntityNodeTemplateIds) { - if (CollectionUtils.isEmpty(entityConsolidationDataList)) { - return true; - } - EntityConsolidationData startingEntityTemplate = - (EntityConsolidationData) entityConsolidationDataList.get(0); - Map<String, Set<GetAttrFuncData>> startingGetAttrOutFuncData = - getConsolidationEntityGetAttrOutFuncData(startingEntityTemplate.getNodesGetAttrOut(), - consolidationEntityNodeTemplateIds); - - for (int i = 1; i < entityConsolidationDataList.size(); i++) { - EntityConsolidationData currentEntityTemplate = - (EntityConsolidationData) entityConsolidationDataList.get(i); - Map<String, Set<GetAttrFuncData>> currentGetAttrOutFuncData = - getConsolidationEntityGetAttrOutFuncData(currentEntityTemplate.getNodesGetAttrOut(), - consolidationEntityNodeTemplateIds); - - if (!isGetAttrRelationToEntitySimilarBetweenEntities(startingGetAttrOutFuncData, - currentGetAttrOutFuncData)) { - return false; - } + private boolean checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal(List entityConsolidationDataList, + Collection<String> consolidationEntityNodeTemplateIds) { + if (CollectionUtils.isEmpty(entityConsolidationDataList)) { + return true; + } + EntityConsolidationData startingEntityTemplate = (EntityConsolidationData) entityConsolidationDataList.get(0); + Map<String, Set<GetAttrFuncData>> startingGetAttrOutFuncData = getConsolidationEntityGetAttrOutFuncData( + startingEntityTemplate.getNodesGetAttrOut(), consolidationEntityNodeTemplateIds); + for (int i = 1; i < entityConsolidationDataList.size(); i++) { + EntityConsolidationData currentEntityTemplate = (EntityConsolidationData) entityConsolidationDataList.get(i); + Map<String, Set<GetAttrFuncData>> currentGetAttrOutFuncData = getConsolidationEntityGetAttrOutFuncData( + currentEntityTemplate.getNodesGetAttrOut(), consolidationEntityNodeTemplateIds); + if (!isGetAttrRelationToEntitySimilarBetweenEntities(startingGetAttrOutFuncData, currentGetAttrOutFuncData)) { + return false; + } + } + return true; } - return true; - } + private boolean isGetAttrRelationToEntitySimilarBetweenEntities(Map<String, Set<GetAttrFuncData>> firstMap, + Map<String, Set<GetAttrFuncData>> secondMap) { + if (MapUtils.isEmpty(firstMap) != MapUtils.isEmpty(secondMap)) { + return false; + } + return (MapUtils.isEmpty(firstMap) && MapUtils.isEmpty(secondMap)) || (new ArrayList<>(firstMap.values()) + .equals(new ArrayList<>(secondMap.values()))); + } - private boolean isGetAttrRelationToEntitySimilarBetweenEntities( - Map<String, Set<GetAttrFuncData>> firstMap, - Map<String, Set<GetAttrFuncData>> secondMap) { - if (MapUtils.isEmpty(firstMap) != MapUtils.isEmpty(secondMap)) { - return false; + private boolean checkSubInterfaceConsolidationPreCondition(ServiceTemplate serviceTemplate, ConsolidationData consolidationData, + TypeComputeConsolidationData typeComputeConsolidationData) { + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + if (Objects.isNull(filePortConsolidationData)) { + return true; + } + Map<String, List<String>> portTypeToPortIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + Collection<String> computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + for (List<String> portIdsFromSameType : portTypeToPortIds.values()) { + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getAllPortTemplateConsolidationData(portIdsFromSameType, + filePortConsolidationData); + if (!areSubInterfacePreConditionRulesValid(portTypeToPortIds, computeNodeTemplateIds, portTemplateConsolidationDataList, + portTemplateConsolidationDataList.get(0))) { + return false; + } + } + return true; } - return (MapUtils.isEmpty(firstMap) && MapUtils.isEmpty(secondMap)) || - (new ArrayList<>(firstMap.values()).equals(new ArrayList<>(secondMap.values()))); + private boolean areSubInterfacePreConditionRulesValid(Map<String, List<String>> portTypeToPortIds, Collection<String> computeNodeTemplateIds, + List<PortTemplateConsolidationData> portTemplateConsolidationDataList, + PortTemplateConsolidationData subInterfaceConsolidationData) { + return areSubInterfaceTypesSimilarBetweenPorts(portTemplateConsolidationDataList, subInterfaceConsolidationData) + && isNumberOfSubInterfacesPerTypeSimilar(portTemplateConsolidationDataList, subInterfaceConsolidationData) + && isGetAttrFromSubInterfaceToOtherEntitiesLegal(computeNodeTemplateIds, portTypeToPortIds, portTemplateConsolidationDataList); + } - } + private boolean isGetAttrFromSubInterfaceToOtherEntitiesLegal(Collection<String> computeNodeTemplateIds, + Map<String, List<String>> portTypeToPortIds, + List<PortTemplateConsolidationData> portTemplateConsolidationDataList) { + ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfacesFromSameTypeFromPorts = collectAllSubInterfacesFromSameTypeFromPorts( + portTemplateConsolidationDataList); + List<SubInterfaceTemplateConsolidationData> subInterfaceList = new ArrayList<>(subInterfacesFromSameTypeFromPorts.values()); + return areGetAttrRelationshipsBetweenSubInterfaceToConsolidationEntitiesValid(computeNodeTemplateIds, portTypeToPortIds, + portTemplateConsolidationDataList, subInterfaceList); + } - private boolean checkSubInterfaceConsolidationPreCondition(ServiceTemplate serviceTemplate, - ConsolidationData consolidationData, - TypeComputeConsolidationData typeComputeConsolidationData) { - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData() - .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + private boolean areGetAttrRelationshipsBetweenSubInterfaceToConsolidationEntitiesValid(Collection<String> computeNodeTemplateIds, + Map<String, List<String>> portTypeToPortIds, + List<PortTemplateConsolidationData> portTemplateConsolidationDataList, + List<SubInterfaceTemplateConsolidationData> subInterfaceList) { + return checkGetAttrOutFromEntityToPortIsLegal(subInterfaceList, portTypeToPortIds) + && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal(portTemplateConsolidationDataList, + getSubInterfaceIdsFromSameType(subInterfaceList)) && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( + subInterfaceList, computeNodeTemplateIds); + } - if (Objects.isNull(filePortConsolidationData)) { - return true; + private boolean areSubInterfaceTypesSimilarBetweenPorts(List<PortTemplateConsolidationData> portTemplateConsolidationDataList, + PortTemplateConsolidationData subInterfaceConsolidationData) { + return portTemplateConsolidationDataList.stream().allMatch(element -> element.hasSameSubInterfaceTypes(subInterfaceConsolidationData)); } - Map<String, List<String>> portTypeToPortIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + private boolean isNumberOfSubInterfacesPerTypeSimilar(List<PortTemplateConsolidationData> portTemplateConsolidationDataList, + PortTemplateConsolidationData subInterfaceConsolidationData) { + return portTemplateConsolidationDataList.stream() + .allMatch(element -> element.isNumberOfSubInterfacesPerTypeSimilar(subInterfaceConsolidationData)); + } - Collection<String> computeNodeTemplateIds = - typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + private Map<String, Set<GetAttrFuncData>> getConsolidationEntityGetAttrOutFuncData(Map<String, List<GetAttrFuncData>> nodesGetAttrOut, + Collection<String> computeNodeTemplateIds) { + Map<String, Set<GetAttrFuncData>> computeGetAttrFuncData = new HashMap<>(); + if (MapUtils.isEmpty(nodesGetAttrOut)) { + return computeGetAttrFuncData; + } + for (Map.Entry<String, List<GetAttrFuncData>> getAttrFuncEntry : nodesGetAttrOut.entrySet()) { + if (computeNodeTemplateIds.contains(getAttrFuncEntry.getKey())) { + computeGetAttrFuncData.put(getAttrFuncEntry.getKey(), new HashSet<>(getAttrFuncEntry.getValue())); + } + } + return computeGetAttrFuncData; + } - for (List<String> portIdsFromSameType : portTypeToPortIds.values()) { - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getAllPortTemplateConsolidationData(portIdsFromSameType, filePortConsolidationData); + private boolean checkGetAttrBetweenEntityConsolidationOfTheSameType(ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + return areThereGetAttrRelationsBetweenComputesOfSameType(typeComputeConsolidationData) || areThereGetAttrRelationsBetweenPortsOfTheSameType( + serviceTemplate, typeComputeConsolidationData, consolidationData); + } - if (!areSubInterfacePreConditionRulesValid(portTypeToPortIds, computeNodeTemplateIds, - portTemplateConsolidationDataList, portTemplateConsolidationDataList.get(0))) { - return false; - } - } - return true; - } - - private boolean areSubInterfacePreConditionRulesValid(Map<String, List<String>> portTypeToPortIds, - Collection<String> computeNodeTemplateIds, - List<PortTemplateConsolidationData> portTemplateConsolidationDataList, - PortTemplateConsolidationData subInterfaceConsolidationData) { - return areSubInterfaceTypesSimilarBetweenPorts(portTemplateConsolidationDataList, - subInterfaceConsolidationData) - && isNumberOfSubInterfacesPerTypeSimilar(portTemplateConsolidationDataList, - subInterfaceConsolidationData) - && isGetAttrFromSubInterfaceToOtherEntitiesLegal(computeNodeTemplateIds, - portTypeToPortIds, portTemplateConsolidationDataList); - } - - private boolean isGetAttrFromSubInterfaceToOtherEntitiesLegal( - Collection<String> computeNodeTemplateIds, - Map<String, List<String>> portTypeToPortIds, - List<PortTemplateConsolidationData> portTemplateConsolidationDataList) { - - ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfacesFromSameTypeFromPorts = - collectAllSubInterfacesFromSameTypeFromPorts(portTemplateConsolidationDataList); - - List<SubInterfaceTemplateConsolidationData> subInterfaceList = new ArrayList<>(subInterfacesFromSameTypeFromPorts - .values()); - return areGetAttrRelationshipsBetweenSubInterfaceToConsolidationEntitiesValid( - computeNodeTemplateIds, portTypeToPortIds, portTemplateConsolidationDataList, subInterfaceList); - } - - private boolean areGetAttrRelationshipsBetweenSubInterfaceToConsolidationEntitiesValid( - Collection<String> computeNodeTemplateIds, Map<String, List<String>> portTypeToPortIds, - List<PortTemplateConsolidationData> portTemplateConsolidationDataList, - List<SubInterfaceTemplateConsolidationData> subInterfaceList) { - return checkGetAttrOutFromEntityToPortIsLegal(subInterfaceList, portTypeToPortIds) - && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( - portTemplateConsolidationDataList, getSubInterfaceIdsFromSameType(subInterfaceList)) - && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( - subInterfaceList, computeNodeTemplateIds); - } - - private boolean areSubInterfaceTypesSimilarBetweenPorts( - List<PortTemplateConsolidationData> portTemplateConsolidationDataList, - PortTemplateConsolidationData subInterfaceConsolidationData) { - - return portTemplateConsolidationDataList.stream().allMatch( - element -> element.hasSameSubInterfaceTypes(subInterfaceConsolidationData)); - } - - private boolean isNumberOfSubInterfacesPerTypeSimilar( - List<PortTemplateConsolidationData> portTemplateConsolidationDataList, - PortTemplateConsolidationData subInterfaceConsolidationData) { - - return portTemplateConsolidationDataList.stream() - .allMatch(element -> element.isNumberOfSubInterfacesPerTypeSimilar(subInterfaceConsolidationData)); - } - - private Map<String, Set<GetAttrFuncData>> getConsolidationEntityGetAttrOutFuncData( - Map<String, List<GetAttrFuncData>> nodesGetAttrOut, - Collection<String> computeNodeTemplateIds) { - Map<String, Set<GetAttrFuncData>> computeGetAttrFuncData = new HashMap<>(); - - if (MapUtils.isEmpty(nodesGetAttrOut)) { - return computeGetAttrFuncData; - } - - for (Map.Entry<String, List<GetAttrFuncData>> getAttrFuncEntry : nodesGetAttrOut.entrySet()) { - if (computeNodeTemplateIds.contains(getAttrFuncEntry.getKey())) { - computeGetAttrFuncData.put(getAttrFuncEntry.getKey(), new HashSet<>(getAttrFuncEntry - .getValue())); - } - } - - return computeGetAttrFuncData; - } - - private boolean checkGetAttrBetweenEntityConsolidationOfTheSameType( - ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - return areThereGetAttrRelationsBetweenComputesOfSameType(typeComputeConsolidationData) - || areThereGetAttrRelationsBetweenPortsOfTheSameType(serviceTemplate, - typeComputeConsolidationData, consolidationData); - - } - - private boolean areThereGetAttrRelationsBetweenComputesOfSameType( - TypeComputeConsolidationData typeComputeConsolidationData) { - - Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationEntities = - typeComputeConsolidationData.getAllComputeTemplateConsolidationData(); - Collection<String> computeNodeTemplateIds = - typeComputeConsolidationData.getAllComputeNodeTemplateIds(); - - return checkGetAttrRelationsForEntityConsolidationData( - computeTemplateConsolidationEntities, computeNodeTemplateIds, - EntityConsolidationData::getNodesGetAttrIn); - } - - private boolean areThereGetAttrRelationsBetweenPortsOfTheSameType( - ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - Map<String, List<String>> portTypeToPortIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); - - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData().getFilePortConsolidationData( - ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + private boolean areThereGetAttrRelationsBetweenComputesOfSameType(TypeComputeConsolidationData typeComputeConsolidationData) { + Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationEntities = typeComputeConsolidationData + .getAllComputeTemplateConsolidationData(); + Collection<String> computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + return checkGetAttrRelationsForEntityConsolidationData(computeTemplateConsolidationEntities, computeNodeTemplateIds, + EntityConsolidationData::getNodesGetAttrIn); + } + private boolean areThereGetAttrRelationsBetweenPortsOfTheSameType(ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + Map<String, List<String>> portTypeToPortIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); for (List<String> portsOfTheSameTypeIds : portTypeToPortIds.values()) { - List<PortTemplateConsolidationData> portTemplateConsolidationDataOfSameType = - getAllPortTemplateConsolidationData(portsOfTheSameTypeIds, filePortConsolidationData); - if (!checkGetAttrRelationsForEntityConsolidationData(portTemplateConsolidationDataOfSameType, - portsOfTheSameTypeIds, EntityConsolidationData::getNodesGetAttrIn)) { + List<PortTemplateConsolidationData> portTemplateConsolidationDataOfSameType = getAllPortTemplateConsolidationData(portsOfTheSameTypeIds, + filePortConsolidationData); + if (!checkGetAttrRelationsForEntityConsolidationData(portTemplateConsolidationDataOfSameType, portsOfTheSameTypeIds, + EntityConsolidationData::getNodesGetAttrIn)) { return false; } } - return true; } - private boolean areThereGetAttrRelationsBetweenSubInterfacesOfSameType( - List<String> subInterfacesIdsFromSameType, - List<SubInterfaceTemplateConsolidationData> subInterfaceList) { - - return checkGetAttrRelationsForEntityConsolidationData(subInterfaceList, - subInterfacesIdsFromSameType, EntityConsolidationData::getNodesGetAttrIn) - || checkGetAttrRelationsForEntityConsolidationData(subInterfaceList, - subInterfacesIdsFromSameType, EntityConsolidationData::getNodesGetAttrOut); + private boolean areThereGetAttrRelationsBetweenSubInterfacesOfSameType(List<String> subInterfacesIdsFromSameType, + List<SubInterfaceTemplateConsolidationData> subInterfaceList) { + return checkGetAttrRelationsForEntityConsolidationData(subInterfaceList, subInterfacesIdsFromSameType, + EntityConsolidationData::getNodesGetAttrIn) || checkGetAttrRelationsForEntityConsolidationData(subInterfaceList, + subInterfacesIdsFromSameType, EntityConsolidationData::getNodesGetAttrOut); + } - } + private List<PortTemplateConsolidationData> getAllPortTemplateConsolidationData(List<String> portsIds, + FilePortConsolidationData filePortConsolidationData) { + List<PortTemplateConsolidationData> portTemplateConsolidationDataOfSameType = new ArrayList<>(); + for (String portId : portsIds) { + PortTemplateConsolidationData portTemplateConsolidationData = filePortConsolidationData.getPortTemplateConsolidationData(portId); + if (Objects.nonNull(portTemplateConsolidationData)) { + portTemplateConsolidationDataOfSameType.add(portTemplateConsolidationData); + } + } + return portTemplateConsolidationDataOfSameType; + } - private List<PortTemplateConsolidationData> getAllPortTemplateConsolidationData( - List<String> portsIds, - FilePortConsolidationData filePortConsolidationData) { - List<PortTemplateConsolidationData> portTemplateConsolidationDataOfSameType = new ArrayList<>(); + private boolean checkGetAttrRelationsForEntityConsolidationData(Collection entities, Collection<String> nodeTemplateIdsOfTheSameType, + Function<EntityConsolidationData, Map<String, List<GetAttrFuncData>>> getAttrValuesMethod) { + for (Object entity : entities) { + Map<String, List<GetAttrFuncData>> getAttrValue = getAttrValuesMethod.apply((EntityConsolidationData) entity); + Set<String> getAttrNodeIds = getAttrValue == null ? new HashSet<>() : getAttrValue.keySet(); + if (getAttrNodeIds.stream().anyMatch(nodeTemplateIdsOfTheSameType::contains)) { + return true; + } + } + return false; + } - for (String portId : portsIds) { - PortTemplateConsolidationData portTemplateConsolidationData = - filePortConsolidationData.getPortTemplateConsolidationData(portId); - if (Objects.nonNull(portTemplateConsolidationData)) { - portTemplateConsolidationDataOfSameType.add(portTemplateConsolidationData); - } + private boolean checkComputeConsolidation(ServiceTemplate serviceTemplate, TypeComputeConsolidationData typeComputeConsolidationData) { + Collection<String> computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + List<String> propertiesWithIdenticalVal = getComputePropertiesWithIdenticalVal(); + return arePropertiesSimilarBetweenComputeNodeTemplates(serviceTemplate, computeNodeTemplateIds, propertiesWithIdenticalVal) + && checkComputeRelations(typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); } - return portTemplateConsolidationDataOfSameType; - } + private boolean checkComputeRelations(Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationEntities) { + return checkEntityConsolidationDataRelations(computeTemplateConsolidationEntities) && checkComputesRelationsToVolume( + computeTemplateConsolidationEntities); + } - private boolean checkGetAttrRelationsForEntityConsolidationData(Collection entities, - Collection<String> nodeTemplateIdsOfTheSameType, - Function<EntityConsolidationData, Map<String, List<GetAttrFuncData>>> getAttrValuesMethod) { - for (Object entity : entities) { - Map<String, List<GetAttrFuncData>> getAttrValue = - getAttrValuesMethod.apply((EntityConsolidationData) entity); - Set<String> getAttrNodeIds = - getAttrValue == null ? new HashSet<>() - : getAttrValue.keySet(); - if (getAttrNodeIds.stream().anyMatch(nodeTemplateIdsOfTheSameType::contains)) { + private boolean checkEntityConsolidationDataRelations(Collection entities) { + EntityConsolidationData startingEntity = (EntityConsolidationData) entities.iterator().next(); + for (Object entity : entities) { + EntityConsolidationData currentEntity = (EntityConsolidationData) entity; + if (!(checkNodesConnectedInRelations(startingEntity, currentEntity) && (checkNodesConnectedOutRelations(startingEntity, currentEntity)) + && (checkGroupIdsRelations(startingEntity, currentEntity)))) { + return false; + } + } return true; - } } - return false; - } - - - private boolean checkComputeConsolidation( - ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData) { - Collection<String> computeNodeTemplateIds = - typeComputeConsolidationData.getAllComputeNodeTemplateIds(); - List<String> propertiesWithIdenticalVal = getComputePropertiesWithIdenticalVal(); - - return arePropertiesSimilarBetweenComputeNodeTemplates(serviceTemplate, computeNodeTemplateIds, - propertiesWithIdenticalVal) - && checkComputeRelations( - typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); - } - - private boolean checkComputeRelations( - Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationEntities) { - - return checkEntityConsolidationDataRelations(computeTemplateConsolidationEntities) - && checkComputesRelationsToVolume(computeTemplateConsolidationEntities); - } - - private boolean checkEntityConsolidationDataRelations(Collection entities) { - EntityConsolidationData startingEntity = (EntityConsolidationData) entities.iterator().next(); - - for (Object entity : entities) { - EntityConsolidationData currentEntity = (EntityConsolidationData) entity; - if (!(checkNodesConnectedInRelations(startingEntity, currentEntity) - && (checkNodesConnectedOutRelations(startingEntity, currentEntity)) - && (checkGroupIdsRelations(startingEntity, currentEntity)))) { - return false; - } + private boolean checkNodesConnectedInRelations(EntityConsolidationData firstEntity, EntityConsolidationData secondEntity) { + return compareNodeConnectivity(firstEntity.getNodesConnectedIn(), secondEntity.getNodesConnectedIn()); } - return true; - } - - private boolean checkNodesConnectedInRelations(EntityConsolidationData firstEntity, - EntityConsolidationData secondEntity) { - return compareNodeConnectivity(firstEntity.getNodesConnectedIn(), - secondEntity.getNodesConnectedIn()); - } - private boolean checkNodesConnectedOutRelations(EntityConsolidationData firstEntity, - EntityConsolidationData secondEntity) { - return compareNodeConnectivity(firstEntity.getNodesConnectedOut(), - secondEntity.getNodesConnectedOut()); - } - - private boolean compareNodeConnectivity( - Multimap<String, RequirementAssignmentData> firstEntityMap, - Multimap<String, RequirementAssignmentData> secondEntityMap) { + private boolean checkNodesConnectedOutRelations(EntityConsolidationData firstEntity, EntityConsolidationData secondEntity) { + return compareNodeConnectivity(firstEntity.getNodesConnectedOut(), secondEntity.getNodesConnectedOut()); + } + private boolean compareNodeConnectivity(Multimap<String, RequirementAssignmentData> firstEntityMap, + Multimap<String, RequirementAssignmentData> secondEntityMap) { if (CommonUtil.isMultimapEmpty(firstEntityMap) && CommonUtil.isMultimapEmpty(secondEntityMap)) { return true; } - return !CommonUtil.isMultimapEmpty(firstEntityMap) && !CommonUtil.isMultimapEmpty(secondEntityMap) - && equalsIgnoreSuffix(new HashSet<>(firstEntityMap.keySet()),new HashSet<>(secondEntityMap.keySet())); + return !CommonUtil.isMultimapEmpty(firstEntityMap) && !CommonUtil.isMultimapEmpty(secondEntityMap) && equalsIgnoreSuffix( + new HashSet<>(firstEntityMap.keySet()), new HashSet<>(secondEntityMap.keySet())); } - private boolean equalsIgnoreSuffix(Set<String> firstKeySet, Set<String> secondKeySet){ - Set<String> firstKeySetTrimmed = firstKeySet.stream().map(this::trimSuffix).collect(Collectors.toSet()); - Set<String> secondKeySetTrimmed = secondKeySet.stream().map(this::trimSuffix).collect(Collectors.toSet()); - return firstKeySetTrimmed.equals(secondKeySetTrimmed); + private boolean equalsIgnoreSuffix(Set<String> firstKeySet, Set<String> secondKeySet) { + Set<String> firstKeySetTrimmed = firstKeySet.stream().map(this::trimSuffix).collect(Collectors.toSet()); + Set<String> secondKeySetTrimmed = secondKeySet.stream().map(this::trimSuffix).collect(Collectors.toSet()); + return firstKeySetTrimmed.equals(secondKeySetTrimmed); } - private String trimSuffix(String volumeName){ - int suffixPosition = volumeName.lastIndexOf("_"); - return volumeName.substring(0, suffixPosition); + private String trimSuffix(String volumeName) { + int suffixPosition = volumeName.lastIndexOf("_"); + return volumeName.substring(0, suffixPosition); } - private boolean checkGroupIdsRelations(EntityConsolidationData startingEntity, - EntityConsolidationData currentEntity) { - return CollectionUtils.isEmpty(startingEntity.getGroupIds()) - && CollectionUtils.isEmpty(currentEntity.getGroupIds()) - || startingEntity.getGroupIds().equals(currentEntity.getGroupIds()); - - } - - private boolean checkComputesRelationsToVolume( - Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationEntities) { - Iterator<ComputeTemplateConsolidationData> iterator = - computeTemplateConsolidationEntities.iterator(); - - Multimap<String, RequirementAssignmentData> startingVolumes = - iterator.next().getVolumes(); + private boolean checkGroupIdsRelations(EntityConsolidationData startingEntity, EntityConsolidationData currentEntity) { + return CollectionUtils.isEmpty(startingEntity.getGroupIds()) && CollectionUtils.isEmpty(currentEntity.getGroupIds()) || startingEntity + .getGroupIds().equals(currentEntity.getGroupIds()); + } + private boolean checkComputesRelationsToVolume(Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationEntities) { + Iterator<ComputeTemplateConsolidationData> iterator = computeTemplateConsolidationEntities.iterator(); + Multimap<String, RequirementAssignmentData> startingVolumes = iterator.next().getVolumes(); for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationEntities) { - Multimap<String, RequirementAssignmentData> currentVolumes = - compute.getVolumes(); + Multimap<String, RequirementAssignmentData> currentVolumes = compute.getVolumes(); if (!compareNodeConnectivity(startingVolumes, currentVolumes)) { return false; } @@ -534,502 +391,357 @@ public class ConsolidationService { return true; } + private boolean checkPortConsolidation(ServiceTemplate serviceTemplate, TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + return validateWantedPortProperties(serviceTemplate, typeComputeConsolidationData) && checkPortRelations( + ToscaUtil.getServiceTemplateFileName(serviceTemplate), typeComputeConsolidationData, consolidationData); + } - private boolean checkPortConsolidation(ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - return validateWantedPortProperties(serviceTemplate, - typeComputeConsolidationData) - && checkPortRelations(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - typeComputeConsolidationData, consolidationData); - } - - - private boolean validateWantedPortProperties(ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData) { - Map<String, List<String>> portTypeToIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); - + private boolean validateWantedPortProperties(ServiceTemplate serviceTemplate, TypeComputeConsolidationData typeComputeConsolidationData) { + Map<String, List<String>> portTypeToIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); List<String> propertiesWithIdenticalVal = getPortPropertiesWithIdenticalVal(); List<String> propertiesThatNeedToHaveSameUsage = getPortPropertiesThatNeedToHaveSameUsage(); - for (List<String> portsIds : portTypeToIds.values()) { - if (!arePortPropertiesValid( - serviceTemplate, propertiesWithIdenticalVal, propertiesThatNeedToHaveSameUsage, portsIds)) { + if (!arePortPropertiesValid(serviceTemplate, propertiesWithIdenticalVal, propertiesThatNeedToHaveSameUsage, portsIds)) { return false; } } - return true; } - private boolean arePortPropertiesValid(ServiceTemplate serviceTemplate, - List<String> propertiesWithIdenticalVal, - List<String> propertiesThatNeedToHaveSameUsage, - List<String> portsIds) { - Map<String, NodeTemplate> nodeTemplates = - serviceTemplate.getTopology_template().getNode_templates(); - - Predicate<String> similar = property -> - isPropertyValueSimilarBetweenNodeTemplates(property, - portsIds, nodeTemplates); - - Predicate<String> exists = property -> - isPropertyUsageSimilarBetweenAllNodeTemplates(property, - portsIds, nodeTemplates); - - return areWantedPortPropertiesValid( - propertiesWithIdenticalVal, similar) - && areWantedPortPropertiesValid( - propertiesThatNeedToHaveSameUsage, exists); - } - - private boolean checkPortRelations(String serviceTemplateName, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - Map<String, List<String>> portTypeToIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + private boolean arePortPropertiesValid(ServiceTemplate serviceTemplate, List<String> propertiesWithIdenticalVal, + List<String> propertiesThatNeedToHaveSameUsage, List<String> portsIds) { + Map<String, NodeTemplate> nodeTemplates = serviceTemplate.getTopology_template().getNode_templates(); + Predicate<String> similar = property -> isPropertyValueSimilarBetweenNodeTemplates(property, portsIds, nodeTemplates); + Predicate<String> exists = property -> isPropertyUsageSimilarBetweenAllNodeTemplates(property, portsIds, nodeTemplates); + return areWantedPortPropertiesValid(propertiesWithIdenticalVal, similar) && areWantedPortPropertiesValid(propertiesThatNeedToHaveSameUsage, + exists); + } + private boolean checkPortRelations(String serviceTemplateName, TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + Map<String, List<String>> portTypeToIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); for (List<String> portIds : portTypeToIds.values()) { - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - collectAllPortsTemplateConsolidationData(portIds, serviceTemplateName, consolidationData); - + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = collectAllPortsTemplateConsolidationData(portIds, + serviceTemplateName, consolidationData); if (!checkEntityConsolidationDataRelations(portTemplateConsolidationDataList) || !checkSubInterfaceRules( - portTemplateConsolidationDataList)) { + portTemplateConsolidationDataList)) { return false; } } - return true; } - private boolean checkSubInterfaceRules(List<PortTemplateConsolidationData> - portTemplateConsolidationDataList) { - ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceTypeToEntity = - collectAllSubInterfacesFromSameTypeFromPorts(portTemplateConsolidationDataList); - List<SubInterfaceTemplateConsolidationData> subInterfaceList = new ArrayList<>(subInterfaceTypeToEntity.values()); - return areSubInterfacePropertiesAndRelationsValid(subInterfaceList); - } - - private boolean areSubInterfacePropertiesAndRelationsValid( - List<SubInterfaceTemplateConsolidationData> subInterfaceList) { - return isResourceGroupPropertiesSimilarBetweenSubPorts(subInterfaceList) - && checkSubInterfaceRelations(subInterfaceList) - && !areThereGetAttrRelationsBetweenSubInterfacesOfSameType( - getSubInterfaceIdsFromSameType(subInterfaceList), subInterfaceList); - } - - private boolean checkSubInterfaceRelations(List<SubInterfaceTemplateConsolidationData> - subInterfaceList) { - return CollectionUtils.isEmpty(subInterfaceList) - || checkEntityConsolidationDataRelations(subInterfaceList); - } - - private boolean isResourceGroupPropertiesSimilarBetweenSubPorts( - List<SubInterfaceTemplateConsolidationData> subInterfaceList) { - if (CollectionUtils.isEmpty(subInterfaceList)) { - return true; - } - - SubInterfaceTemplateConsolidationData startingSubInterface = subInterfaceList.get(0); - for (SubInterfaceTemplateConsolidationData subInterface : subInterfaceList) { - if (!startingSubInterface.getResourceGroupCount().equals(subInterface.getResourceGroupCount()) - || !StringUtils.equals(startingSubInterface.getNetworkRole(), subInterface.getNetworkRole())) { - return false; - } + private boolean checkSubInterfaceRules(List<PortTemplateConsolidationData> portTemplateConsolidationDataList) { + ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceTypeToEntity = collectAllSubInterfacesFromSameTypeFromPorts( + portTemplateConsolidationDataList); + List<SubInterfaceTemplateConsolidationData> subInterfaceList = new ArrayList<>(subInterfaceTypeToEntity.values()); + return areSubInterfacePropertiesAndRelationsValid(subInterfaceList); } - return true; - } - - private List<String> getSubInterfaceIdsFromSameType(List<SubInterfaceTemplateConsolidationData> - subInterfaceList) { - if (CollectionUtils.isEmpty(subInterfaceList)) { - return new ArrayList<>(); + private boolean areSubInterfacePropertiesAndRelationsValid(List<SubInterfaceTemplateConsolidationData> subInterfaceList) { + return isResourceGroupPropertiesSimilarBetweenSubPorts(subInterfaceList) && checkSubInterfaceRelations(subInterfaceList) + && !areThereGetAttrRelationsBetweenSubInterfacesOfSameType(getSubInterfaceIdsFromSameType(subInterfaceList), subInterfaceList); } - return subInterfaceList.stream().map(SubInterfaceTemplateConsolidationData::getNodeTemplateId) - .collect(Collectors.toList()); - } + private boolean checkSubInterfaceRelations(List<SubInterfaceTemplateConsolidationData> subInterfaceList) { + return CollectionUtils.isEmpty(subInterfaceList) || checkEntityConsolidationDataRelations(subInterfaceList); + } - private ListMultimap<String, SubInterfaceTemplateConsolidationData> collectAllSubInterfacesFromSameTypeFromPorts( - List<PortTemplateConsolidationData> portTemplateConsolidationDataList) { - ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceTypeToEntity = ArrayListMultimap.create(); - for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { - portTemplateConsolidationData.copyMappedInto(subInterfaceTypeToEntity); + private boolean isResourceGroupPropertiesSimilarBetweenSubPorts(List<SubInterfaceTemplateConsolidationData> subInterfaceList) { + if (CollectionUtils.isEmpty(subInterfaceList)) { + return true; + } + SubInterfaceTemplateConsolidationData startingSubInterface = subInterfaceList.get(0); + for (SubInterfaceTemplateConsolidationData subInterface : subInterfaceList) { + if (!startingSubInterface.getResourceGroupCount().equals(subInterface.getResourceGroupCount()) || !StringUtils + .equals(startingSubInterface.getNetworkRole(), subInterface.getNetworkRole())) { + return false; + } + } + return true; } - return subInterfaceTypeToEntity; - } + private List<String> getSubInterfaceIdsFromSameType(List<SubInterfaceTemplateConsolidationData> subInterfaceList) { + if (CollectionUtils.isEmpty(subInterfaceList)) { + return new ArrayList<>(); + } + return subInterfaceList.stream().map(SubInterfaceTemplateConsolidationData::getNodeTemplateId).collect(Collectors.toList()); + } - private List<PortTemplateConsolidationData> collectAllPortsTemplateConsolidationData(List<String> portIds, - String serviceTemplateName, - ConsolidationData consolidationData) { + private ListMultimap<String, SubInterfaceTemplateConsolidationData> collectAllSubInterfacesFromSameTypeFromPorts( + List<PortTemplateConsolidationData> portTemplateConsolidationDataList) { + ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceTypeToEntity = ArrayListMultimap.create(); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + portTemplateConsolidationData.copyMappedInto(subInterfaceTypeToEntity); + } + return subInterfaceTypeToEntity; + } - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData() + private List<PortTemplateConsolidationData> collectAllPortsTemplateConsolidationData(List<String> portIds, String serviceTemplateName, + ConsolidationData consolidationData) { + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() .getFilePortConsolidationData(serviceTemplateName); - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = new ArrayList<>(); - - for (String portId : portIds) { - PortTemplateConsolidationData portTemplateConsolidationData = filePortConsolidationData - .getPortTemplateConsolidationData(portId); - if (Objects.nonNull(portTemplateConsolidationData)) { - portTemplateConsolidationDataList.add(portTemplateConsolidationData); - } + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = new ArrayList<>(); + for (String portId : portIds) { + PortTemplateConsolidationData portTemplateConsolidationData = filePortConsolidationData.getPortTemplateConsolidationData(portId); + if (Objects.nonNull(portTemplateConsolidationData)) { + portTemplateConsolidationDataList.add(portTemplateConsolidationData); + } + } + return portTemplateConsolidationDataList; } - return portTemplateConsolidationDataList; - } - - private boolean areWantedPortPropertiesValid(List<String> propertiesToCheck, - Predicate<String> condition) { - - return propertiesToCheck.stream().allMatch(condition); - } - - - private boolean arePropertiesSimilarBetweenComputeNodeTemplates( - ServiceTemplate serviceTemplate, - Collection<String> computeNodeTemplateIds, - List<String> propertiesThatNeedToBeSimilar) { - - Map<String, NodeTemplate> idToNodeTemplate = - serviceTemplate.getTopology_template().getNode_templates(); - - for (String property : propertiesThatNeedToBeSimilar) { - if (!isPropertyValueSimilarBetweenNodeTemplates(property, computeNodeTemplateIds, - idToNodeTemplate)) { - return false; - } - } - return true; - } - - private boolean isPropertyUsageSimilarBetweenAllNodeTemplates(String propertyToCheck, - List<String> entityNodeTemplateIds, - Map<String, NodeTemplate> idToNodeTemplate) { - NodeTemplate startingNodeTemplate = idToNodeTemplate.get(entityNodeTemplateIds.get(0)); - if (Objects.isNull(startingNodeTemplate)) { - throw new CoreException( - new DuplicateResourceIdsInDifferentFilesErrorBuilder(entityNodeTemplateIds.get(0)) - .build()); - } - - boolean propertyExistCondition = - isPropertyExistInNodeTemplate(propertyToCheck, startingNodeTemplate); - - for (int i = 1; i < entityNodeTemplateIds.size(); i++) { - NodeTemplate currentNodeTemplate = idToNodeTemplate.get(entityNodeTemplateIds.get(i)); - if (Objects.isNull(currentNodeTemplate)) { - throw new CoreException( - new DuplicateResourceIdsInDifferentFilesErrorBuilder(entityNodeTemplateIds.get(i)) - .build()); - } - if (propertyExistCondition != isPropertyExistInNodeTemplate(propertyToCheck, currentNodeTemplate)) { - return false; - } + private boolean areWantedPortPropertiesValid(List<String> propertiesToCheck, Predicate<String> condition) { + return propertiesToCheck.stream().allMatch(condition); } - return true; - - } - - private boolean isPropertyValueSimilarBetweenNodeTemplates(String propertyToCheck, - Collection<String> entityNodeTemplateIds, - Map<String, NodeTemplate> idToNodeTemplate) { - - Set<Object> propertiesValues = new HashSet<>(); - Iterator<String> iterator = entityNodeTemplateIds.iterator(); - - handlePropertyValue(propertyToCheck, idToNodeTemplate, propertiesValues, iterator.next()); - - while (iterator.hasNext()) { - handlePropertyValue(propertyToCheck, idToNodeTemplate, propertiesValues, iterator.next()); + private boolean arePropertiesSimilarBetweenComputeNodeTemplates(ServiceTemplate serviceTemplate, Collection<String> computeNodeTemplateIds, + List<String> propertiesThatNeedToBeSimilar) { + Map<String, NodeTemplate> idToNodeTemplate = serviceTemplate.getTopology_template().getNode_templates(); + for (String property : propertiesThatNeedToBeSimilar) { + if (!isPropertyValueSimilarBetweenNodeTemplates(property, computeNodeTemplateIds, idToNodeTemplate)) { + return false; + } + } + return true; } - return propertiesValues.size() == 1; - } - - private void handlePropertyValue(String propertyToCheck, - Map<String, NodeTemplate> idToNodeTemplate, - Set<Object> propertiesValues, String nodeId) { - NodeTemplate startingNodeTemplate = idToNodeTemplate.get(nodeId); - if (Objects.isNull(startingNodeTemplate)) { - throw new CoreException( - new DuplicateResourceIdsInDifferentFilesErrorBuilder(nodeId) - .build()); + private boolean isPropertyUsageSimilarBetweenAllNodeTemplates(String propertyToCheck, List<String> entityNodeTemplateIds, + Map<String, NodeTemplate> idToNodeTemplate) { + NodeTemplate startingNodeTemplate = idToNodeTemplate.get(entityNodeTemplateIds.get(0)); + if (Objects.isNull(startingNodeTemplate)) { + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(entityNodeTemplateIds.get(0)).build()); + } + boolean propertyExistCondition = isPropertyExistInNodeTemplate(propertyToCheck, startingNodeTemplate); + for (int i = 1; i < entityNodeTemplateIds.size(); i++) { + NodeTemplate currentNodeTemplate = idToNodeTemplate.get(entityNodeTemplateIds.get(i)); + if (Objects.isNull(currentNodeTemplate)) { + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(entityNodeTemplateIds.get(i)).build()); + } + if (propertyExistCondition != isPropertyExistInNodeTemplate(propertyToCheck, currentNodeTemplate)) { + return false; + } + } + return true; } - addPropertyValue(propertyToCheck, startingNodeTemplate, propertiesValues); - } + private boolean isPropertyValueSimilarBetweenNodeTemplates(String propertyToCheck, Collection<String> entityNodeTemplateIds, + Map<String, NodeTemplate> idToNodeTemplate) { + Set<Object> propertiesValues = new HashSet<>(); + Iterator<String> iterator = entityNodeTemplateIds.iterator(); + handlePropertyValue(propertyToCheck, idToNodeTemplate, propertiesValues, iterator.next()); + while (iterator.hasNext()) { + handlePropertyValue(propertyToCheck, idToNodeTemplate, propertiesValues, iterator.next()); + } + return propertiesValues.size() == 1; + } - private void addPropertyValue(String property, - NodeTemplate nodeTemplate, - Set<Object> propertiesValues) { - propertiesValues.add( - isPropertyExistInNodeTemplate(property, nodeTemplate) ? nodeTemplate.getProperties() - .get(property) : ""); - } + private void handlePropertyValue(String propertyToCheck, Map<String, NodeTemplate> idToNodeTemplate, Set<Object> propertiesValues, + String nodeId) { + NodeTemplate startingNodeTemplate = idToNodeTemplate.get(nodeId); + if (Objects.isNull(startingNodeTemplate)) { + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(nodeId).build()); + } + addPropertyValue(propertyToCheck, startingNodeTemplate, propertiesValues); + } - private boolean isPropertyExistInNodeTemplate(String propertyToCheck, NodeTemplate nodeTemplate) { - return !(nodeTemplate.getProperties() == null - || nodeTemplate.getProperties().get(propertyToCheck) == null); - } + private void addPropertyValue(String property, NodeTemplate nodeTemplate, Set<Object> propertiesValues) { + propertiesValues.add(isPropertyExistInNodeTemplate(property, nodeTemplate) ? nodeTemplate.getProperties().get(property) : ""); + } - void substitutionServiceTemplateConsolidation(String substituteNodeTemplateId, - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - TranslationContext translationContext) { + private boolean isPropertyExistInNodeTemplate(String propertyToCheck, NodeTemplate nodeTemplate) { + return !(nodeTemplate.getProperties() == null || nodeTemplate.getProperties().get(propertyToCheck) == null); + } + void substitutionServiceTemplateConsolidation(String substituteNodeTemplateId, ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, TranslationContext translationContext) { ConsolidationData consolidationData = translationContext.getConsolidationData(); - - boolean substitutionConsolidationRuleResult = - substitutionServiceTemplateConsolidationRule(substitutionServiceTemplate, translationContext); - + boolean substitutionConsolidationRuleResult = substitutionServiceTemplateConsolidationRule(substitutionServiceTemplate, translationContext); if (substitutionConsolidationRuleResult) { - List<UnifiedCompositionData> unifiedCompositionDataList = - createSubstitutionUnifiedCompositionDataList(substituteNodeTemplateId, serviceTemplate, - substitutionServiceTemplate, consolidationData); - unifiedCompositionService - .createUnifiedComposition(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, - UnifiedCompositionMode.NestedSingleCompute, translationContext); + List<UnifiedCompositionData> unifiedCompositionDataList = createSubstitutionUnifiedCompositionDataList(substituteNodeTemplateId, + serviceTemplate, substitutionServiceTemplate, consolidationData); + unifiedCompositionService.createUnifiedComposition(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, + UnifiedCompositionMode.NestedSingleCompute, translationContext); } else { //The node template does not represent unified VFC but complexVFC - //Adding the id in the context for fixing connectivity from/to nested non-unified nodes - translationContext.addUnifiedNestedNodeTemplateId(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - substituteNodeTemplateId, substituteNodeTemplateId); + //Adding the id in the context for fixing connectivity from/to nested non-unified nodes + translationContext.addUnifiedNestedNodeTemplateId(ToscaUtil.getServiceTemplateFileName(serviceTemplate), substituteNodeTemplateId, + substituteNodeTemplateId); if (!translationContext.isUnifiedHandledServiceTemplate(substitutionServiceTemplate)) { serviceTemplateConsolidation(substitutionServiceTemplate, translationContext); } } } - private boolean substitutionServiceTemplateConsolidationRule(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { + private boolean substitutionServiceTemplateConsolidationRule(ServiceTemplate nestedServiceTemplate, TranslationContext context) { ConsolidationData consolidationData = context.getConsolidationData(); - - return consolidationData.getComputeConsolidationDataHandler().isNumberOfComputeTypesLegal( - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)) - && !isThereMoreThanOneNestedLevel(nestedServiceTemplate, context); + return consolidationData.getComputeConsolidationDataHandler() + .isNumberOfComputeTypesLegal(ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)) && !isThereMoreThanOneNestedLevel( + nestedServiceTemplate, context); } - private boolean isThereMoreThanOneNestedLevel(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { + private boolean isThereMoreThanOneNestedLevel(ServiceTemplate nestedServiceTemplate, TranslationContext context) { String nestedServiceTemplateName = ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate); if (Objects.isNull(nestedServiceTemplateName)) { return false; } - NestedConsolidationDataHandler nestedConsolidationDataHandler = context.getNestedConsolidationDataHandler(); - //Condition to check if there is nested file and if file contains only sub interfaces then + // return false - return nestedConsolidationDataHandler.isNestedConsolidationDataExist(nestedServiceTemplateName) - && !ifNestedFileContainsOnlySubInterface(nestedServiceTemplate, context); + return nestedConsolidationDataHandler.isNestedConsolidationDataExist(nestedServiceTemplateName) && !ifNestedFileContainsOnlySubInterface( + nestedServiceTemplate, context); } private boolean ifNestedFileContainsOnlySubInterface(ServiceTemplate serviceTemplate, TranslationContext context) { Map<String, NodeTemplate> nestedNodeTemplateMap = DataModelUtil.getNodeTemplates(serviceTemplate); - Set<String> nestedHeatFileNames = getNestedHeatFileNames(nestedNodeTemplateMap); - return ifAllResourceAreSubInterface(nestedHeatFileNames, context); } private Set<String> getNestedHeatFileNames(Map<String, NodeTemplate> nestedNodeTemplateMap) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - - return nestedNodeTemplateMap.entrySet().stream() - .filter(entry -> toscaAnalyzerService.isSubstitutableNodeTemplate(entry.getValue()) - && toscaAnalyzerService.getSubstituteServiceTemplateName( - entry.getKey(), entry.getValue()).isPresent()) - .map(entry -> toscaAnalyzerService.getSubstituteServiceTemplateName( - entry.getKey(), entry.getValue()).get()) - .collect(Collectors.toSet()); + return nestedNodeTemplateMap.entrySet().stream().filter( + entry -> toscaAnalyzerService.isSubstitutableNodeTemplate(entry.getValue()) && toscaAnalyzerService + .getSubstituteServiceTemplateName(entry.getKey(), entry.getValue()).isPresent()) + .map(entry -> toscaAnalyzerService.getSubstituteServiceTemplateName(entry.getKey(), entry.getValue()).get()).collect(Collectors.toSet()); } // Method returns true if all of the resource are sub interface - private boolean ifAllResourceAreSubInterface(Set<String> nestedHeatFileNames, - TranslationContext context) { + private boolean ifAllResourceAreSubInterface(Set<String> nestedHeatFileNames, TranslationContext context) { if (nestedHeatFileNames.isEmpty()) { - return true; + return true; } - for (String fileName : nestedHeatFileNames) { String heatFileName = context.getNestedHeatFileName().get(fileName); - - if (Objects.nonNull(heatFileName) - && !context.getTranslatedServiceTemplates().get(heatFileName).getTopology_template() - .getNode_templates().values().stream() - .allMatch(nodeTemplate -> ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE - .equals(nodeTemplate.getType()))) { + if (Objects.nonNull(heatFileName) && !context.getTranslatedServiceTemplates().get(heatFileName).getTopology_template().getNode_templates() + .values().stream().allMatch(nodeTemplate -> ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE.equals(nodeTemplate.getType()))) { return false; } } - return true; } - private List<UnifiedCompositionData> createUnifiedCompositionDataList( - ServiceTemplate serviceTemplate, - ConsolidationData consolidationData, - TypeComputeConsolidationData typeComputeConsolidationData) { - - List<UnifiedCompositionData> unifiedCompositionDataList = new ArrayList<>(); - - for (ComputeTemplateConsolidationData computeTemplateConsolidationData : typeComputeConsolidationData - .getAllComputeTemplateConsolidationData()) { - UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); - unifiedCompositionData.setComputeTemplateConsolidationData(computeTemplateConsolidationData); - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData().getFilePortConsolidationData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate)); - setUnifiedCompositionDataWithPortTemplateData(computeTemplateConsolidationData, filePortConsolidationData, - unifiedCompositionData); - unifiedCompositionDataList.add(unifiedCompositionData); - } - return unifiedCompositionDataList; - } - - private void setPortTemplateConsolidationData(FilePortConsolidationData filePortConsolidationData, - String portId, - UnifiedCompositionData unifiedCompositionData, - List<SubInterfaceTemplateConsolidationData> - subInterfaceTemplateConsolidationDataList) { - if (Objects.isNull(filePortConsolidationData)) { - return; - } - PortTemplateConsolidationData portTemplateConsolidationData = - filePortConsolidationData.getPortTemplateConsolidationData(portId); - unifiedCompositionData.addPortTemplateConsolidationData(portTemplateConsolidationData); - if (portTemplateConsolidationData != null) { - portTemplateConsolidationData.copyFlatInto(subInterfaceTemplateConsolidationDataList); - } - } - - private List<UnifiedCompositionData> createSubstitutionUnifiedCompositionDataList( - String substituteNodeTemplateId, - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - ConsolidationData consolidationData) { - List<UnifiedCompositionData> unifiedCompositionDataList = new ArrayList<>(); - FileNestedConsolidationData fileNestedConsolidationData = - consolidationData.getNestedConsolidationData() + private List<UnifiedCompositionData> createUnifiedCompositionDataList(ServiceTemplate serviceTemplate, ConsolidationData consolidationData, + TypeComputeConsolidationData typeComputeConsolidationData) { + List<UnifiedCompositionData> unifiedCompositionDataList = new ArrayList<>(); + for (ComputeTemplateConsolidationData computeTemplateConsolidationData : typeComputeConsolidationData + .getAllComputeTemplateConsolidationData()) { + UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); + unifiedCompositionData.setComputeTemplateConsolidationData(computeTemplateConsolidationData); + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + setUnifiedCompositionDataWithPortTemplateData(computeTemplateConsolidationData, filePortConsolidationData, unifiedCompositionData); + unifiedCompositionDataList.add(unifiedCompositionData); + } + return unifiedCompositionDataList; + } + + private void setPortTemplateConsolidationData(FilePortConsolidationData filePortConsolidationData, String portId, + UnifiedCompositionData unifiedCompositionData, + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList) { + if (Objects.isNull(filePortConsolidationData)) { + return; + } + PortTemplateConsolidationData portTemplateConsolidationData = filePortConsolidationData.getPortTemplateConsolidationData(portId); + unifiedCompositionData.addPortTemplateConsolidationData(portTemplateConsolidationData); + if (portTemplateConsolidationData != null) { + portTemplateConsolidationData.copyFlatInto(subInterfaceTemplateConsolidationDataList); + } + } + + private List<UnifiedCompositionData> createSubstitutionUnifiedCompositionDataList(String substituteNodeTemplateId, + ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + ConsolidationData consolidationData) { + List<UnifiedCompositionData> unifiedCompositionDataList = new ArrayList<>(); + FileNestedConsolidationData fileNestedConsolidationData = consolidationData.getNestedConsolidationData() .getFileNestedConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + if (Objects.nonNull(fileNestedConsolidationData)) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = fileNestedConsolidationData + .getNestedTemplateConsolidationData(substituteNodeTemplateId); + UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); + unifiedCompositionData.setNestedTemplateConsolidationData(nestedTemplateConsolidationData); + unifiedCompositionDataList.add(unifiedCompositionData); + addSubInterfaceDataToNestedCompositionData(substitutionServiceTemplate, consolidationData, unifiedCompositionData); + } + return unifiedCompositionDataList; + } - if (Objects.nonNull(fileNestedConsolidationData)) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = - fileNestedConsolidationData.getNestedTemplateConsolidationData(substituteNodeTemplateId); - UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); - unifiedCompositionData.setNestedTemplateConsolidationData(nestedTemplateConsolidationData); - unifiedCompositionDataList.add(unifiedCompositionData); - addSubInterfaceDataToNestedCompositionData(substitutionServiceTemplate, consolidationData, - unifiedCompositionData); - } - - return unifiedCompositionDataList; - } - - private void addSubInterfaceDataToNestedCompositionData(ServiceTemplate substitutionServiceTemplate, - ConsolidationData consolidationData, - UnifiedCompositionData unifiedCompositionData) { - FileComputeConsolidationData nestedFileComputeConsolidationData = consolidationData.getComputeConsolidationData() - .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate)); - FilePortConsolidationData nestedFilePortConsolidationData = consolidationData.getPortConsolidationData() - .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate)); - if (Objects.isNull(nestedFileComputeConsolidationData) - || Objects.isNull(nestedFilePortConsolidationData)) { - return; - } - TypeComputeConsolidationData computeType = - nestedFileComputeConsolidationData.getAllTypeComputeConsolidationData().iterator().next(); - if (Objects.isNull(computeType)) { - return; - } - ComputeTemplateConsolidationData computeTemplateConsolidationData = - computeType.getAllComputeTemplateConsolidationData().iterator().next(); - setUnifiedCompositionDataWithPortTemplateData(computeTemplateConsolidationData, nestedFilePortConsolidationData, - unifiedCompositionData); - } - - private void setUnifiedCompositionDataWithPortTemplateData(ComputeTemplateConsolidationData - computeTemplateConsolidationData, - FilePortConsolidationData filePortConsolidationData, - UnifiedCompositionData unifiedCompositionData) { - Collection<List<String>> portCollection = - computeTemplateConsolidationData.getPorts() == null ? Collections.emptyList() - : computeTemplateConsolidationData.getPorts().values(); - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = new ArrayList<>(); - portCollection.stream() - .flatMap(Collection::stream) - .forEach(portId -> setPortTemplateConsolidationData(filePortConsolidationData, portId, - unifiedCompositionData, subInterfaceTemplateConsolidationDataList)); - unifiedCompositionData.setSubInterfaceTemplateConsolidationDataList( - subInterfaceTemplateConsolidationDataList); - } - - private boolean consolidationPreCondition( - ServiceTemplate serviceTemplate, - ConsolidationData consolidationData, - TypeComputeConsolidationData typeComputeConsolidationData) { - - return (typeComputeConsolidationData.isThereMoreThanOneComputeTypeInstance() - && typeComputeConsolidationData.isNumberOfPortsEqualsBetweenComputeNodes() - && typeComputeConsolidationData.isNumberOfPortFromEachTypeLegal() - && typeComputeConsolidationData.isPortTypesEqualsBetweenComputeNodes() - && checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType(serviceTemplate, - typeComputeConsolidationData, consolidationData) - && checkSubInterfaceConsolidationPreCondition(serviceTemplate, consolidationData, - typeComputeConsolidationData)); - - } - - List<String> getPropertiesWithIdenticalVal(UnifiedCompositionEntity entity) { - switch (entity) { - case COMPUTE: - return getComputePropertiesWithIdenticalVal(); - - case OTHER: - return getComputePropertiesWithIdenticalVal(); - - case PORT: - return getPortPropertiesWithIdenticalVal(); - - default: - return new ArrayList<>(); - } - } - - private List<String> getComputePropertiesWithIdenticalVal() { - List<String> propertyWithIdenticalValue = new ArrayList<>(); - propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_IMAGE); - propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_FLAVOR); - return propertyWithIdenticalValue; - } - - private List<String> getPortPropertiesWithIdenticalVal() { - List<String> propertiesThatNeedToHaveIdenticalVal = new ArrayList<>(); - propertiesThatNeedToHaveIdenticalVal.add(ToscaConstants.PORT_ALLOWED_ADDRESS_PAIRS); - propertiesThatNeedToHaveIdenticalVal.add(ToscaConstants.MAC_ADDRESS); - - propertiesThatNeedToHaveIdenticalVal - .addAll(TranslationContext.getEnrichPortResourceProperties()); - - return propertiesThatNeedToHaveIdenticalVal; - } - - private List<String> getPortPropertiesThatNeedToHaveSameUsage() { - List<String> propertiesThatNeedToHaveSameUsage = new ArrayList<>(); - propertiesThatNeedToHaveSameUsage.add(ToscaConstants.PORT_FIXED_IPS); - propertiesThatNeedToHaveSameUsage.add(ToscaConstants.PORT_ALLOWED_ADDRESS_PAIRS); - propertiesThatNeedToHaveSameUsage.add(ToscaConstants.MAC_ADDRESS); - - propertiesThatNeedToHaveSameUsage.addAll(TranslationContext.getEnrichPortResourceProperties()); - - return propertiesThatNeedToHaveSameUsage; - } + private void addSubInterfaceDataToNestedCompositionData(ServiceTemplate substitutionServiceTemplate, ConsolidationData consolidationData, + UnifiedCompositionData unifiedCompositionData) { + FileComputeConsolidationData nestedFileComputeConsolidationData = consolidationData.getComputeConsolidationData() + .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate)); + FilePortConsolidationData nestedFilePortConsolidationData = consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate)); + if (Objects.isNull(nestedFileComputeConsolidationData) || Objects.isNull(nestedFilePortConsolidationData)) { + return; + } + TypeComputeConsolidationData computeType = nestedFileComputeConsolidationData.getAllTypeComputeConsolidationData().iterator().next(); + if (Objects.isNull(computeType)) { + return; + } + ComputeTemplateConsolidationData computeTemplateConsolidationData = computeType.getAllComputeTemplateConsolidationData().iterator().next(); + setUnifiedCompositionDataWithPortTemplateData(computeTemplateConsolidationData, nestedFilePortConsolidationData, unifiedCompositionData); + } + + private void setUnifiedCompositionDataWithPortTemplateData(ComputeTemplateConsolidationData computeTemplateConsolidationData, + FilePortConsolidationData filePortConsolidationData, + UnifiedCompositionData unifiedCompositionData) { + Collection<List<String>> portCollection = + computeTemplateConsolidationData.getPorts() == null ? Collections.emptyList() : computeTemplateConsolidationData.getPorts().values(); + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = new ArrayList<>(); + portCollection.stream().flatMap(Collection::stream).forEach( + portId -> setPortTemplateConsolidationData(filePortConsolidationData, portId, unifiedCompositionData, + subInterfaceTemplateConsolidationDataList)); + unifiedCompositionData.setSubInterfaceTemplateConsolidationDataList(subInterfaceTemplateConsolidationDataList); + } + + private boolean consolidationPreCondition(ServiceTemplate serviceTemplate, ConsolidationData consolidationData, + TypeComputeConsolidationData typeComputeConsolidationData) { + return (typeComputeConsolidationData.isThereMoreThanOneComputeTypeInstance() && typeComputeConsolidationData + .isNumberOfPortsEqualsBetweenComputeNodes() && typeComputeConsolidationData.isNumberOfPortFromEachTypeLegal() + && typeComputeConsolidationData.isPortTypesEqualsBetweenComputeNodes() && checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType( + serviceTemplate, typeComputeConsolidationData, consolidationData) && checkSubInterfaceConsolidationPreCondition(serviceTemplate, + consolidationData, typeComputeConsolidationData)); + } + + List<String> getPropertiesWithIdenticalVal(UnifiedCompositionEntity entity) { + switch (entity) { + case COMPUTE: + return getComputePropertiesWithIdenticalVal(); + case OTHER: + return getComputePropertiesWithIdenticalVal(); + case PORT: + return getPortPropertiesWithIdenticalVal(); + default: + return new ArrayList<>(); + } + } -} + private List<String> getComputePropertiesWithIdenticalVal() { + List<String> propertyWithIdenticalValue = new ArrayList<>(); + propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_IMAGE); + propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_FLAVOR); + return propertyWithIdenticalValue; + } + + private List<String> getPortPropertiesWithIdenticalVal() { + List<String> propertiesThatNeedToHaveIdenticalVal = new ArrayList<>(); + propertiesThatNeedToHaveIdenticalVal.add(ToscaConstants.PORT_ALLOWED_ADDRESS_PAIRS); + propertiesThatNeedToHaveIdenticalVal.add(ToscaConstants.MAC_ADDRESS); + propertiesThatNeedToHaveIdenticalVal.addAll(TranslationContext.getEnrichPortResourceProperties()); + return propertiesThatNeedToHaveIdenticalVal; + } + private List<String> getPortPropertiesThatNeedToHaveSameUsage() { + List<String> propertiesThatNeedToHaveSameUsage = new ArrayList<>(); + propertiesThatNeedToHaveSameUsage.add(ToscaConstants.PORT_FIXED_IPS); + propertiesThatNeedToHaveSameUsage.add(ToscaConstants.PORT_ALLOWED_ADDRESS_PAIRS); + propertiesThatNeedToHaveSameUsage.add(ToscaConstants.MAC_ADDRESS); + propertiesThatNeedToHaveSameUsage.addAll(TranslationContext.getEnrichPortResourceProperties()); + return propertiesThatNeedToHaveSameUsage; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationTypesConnectivity.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationTypesConnectivity.java index a3d434b138..584cbf5fb2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationTypesConnectivity.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationTypesConnectivity.java @@ -26,27 +26,23 @@ import com.google.common.collect.Multimap; public class ConsolidationTypesConnectivity { private static Multimap<ConsolidationEntityType, ConsolidationEntityType> entityToEntitiesWithoutRelationship; - private static ImmutableSet<ConsolidationEntityType> consolidationEntityRelationNodes = ImmutableSet.of( - ConsolidationEntityType.COMPUTE, ConsolidationEntityType.VOLUME, - ConsolidationEntityType.PORT, ConsolidationEntityType.NESTED, + private static ImmutableSet<ConsolidationEntityType> consolidationEntityRelationNodes = ImmutableSet + .of(ConsolidationEntityType.COMPUTE, ConsolidationEntityType.VOLUME, ConsolidationEntityType.PORT, ConsolidationEntityType.NESTED, ConsolidationEntityType.VFC_NESTED); static { - entityToEntitiesWithoutRelationship = - ImmutableSetMultimap.<ConsolidationEntityType, ConsolidationEntityType>builder() - .putAll(ConsolidationEntityType.COMPUTE, consolidationEntityRelationNodes) - .putAll(ConsolidationEntityType.PORT, consolidationEntityRelationNodes) - .putAll(ConsolidationEntityType.VOLUME, consolidationEntityRelationNodes) - .putAll(ConsolidationEntityType.VFC_NESTED, consolidationEntityRelationNodes) - .putAll(ConsolidationEntityType.NESTED, consolidationEntityRelationNodes) - .build(); + entityToEntitiesWithoutRelationship = ImmutableSetMultimap.<ConsolidationEntityType, ConsolidationEntityType>builder() + .putAll(ConsolidationEntityType.COMPUTE, consolidationEntityRelationNodes) + .putAll(ConsolidationEntityType.PORT, consolidationEntityRelationNodes) + .putAll(ConsolidationEntityType.VOLUME, consolidationEntityRelationNodes) + .putAll(ConsolidationEntityType.VFC_NESTED, consolidationEntityRelationNodes) + .putAll(ConsolidationEntityType.NESTED, consolidationEntityRelationNodes).build(); } private ConsolidationTypesConnectivity() { } static boolean isDependsOnRelationshipValid(ConsolidationEntityType source, ConsolidationEntityType target) { - return !entityToEntitiesWithoutRelationship.containsKey(source) - || !entityToEntitiesWithoutRelationship.containsEntry(source, target); + return !entityToEntitiesWithoutRelationship.containsKey(source) || !entityToEntitiesWithoutRelationship.containsEntry(source, target); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java index 7c4b23be27..d5a6d6971b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; public class Constants { @@ -27,19 +26,11 @@ public class Constants { public static final String NAME_PROPERTY_NAME = "name"; public static final String SECURITY_GROUPS_PROPERTY_NAME = "security_groups"; public static final String PORT_PROPERTY_NAME = "port"; - static final String VFC_PARENT_PORT_ROLE = "vfc_parent_port_role"; - static final String SUB_INTERFACE_ROLE = "subinterface_role"; //General public static final String PROP = "properties"; public static final String ATTR = "attributes"; public static final String SERVICE_INSTANCE_PORT_PREFIX = "port_"; public static final String SERVICE_INSTANCE_LINK_PREFIX = "link_"; - static final String GROUP = "group"; - //Unified model - static final String COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX = "vm_"; - static final String COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX = "_name"; - static final String PORT_IDENTICAL_VALUE_PROPERTY_PREFIX = "port_"; - static final String SUB_INTERFACE_PROPERTY_VALUE_PREFIX = "subinterface_"; public static final String ABSTRACT_NODE_TEMPLATE_ID_PREFIX = "abstract_"; public static final String VNF_NODE_TEMPLATE_ID_SUFFIX = "_VNF"; //GlobalTypesServiceTemplates @@ -48,6 +39,14 @@ public class Constants { public static final String FAILED_TO_GENERATE_GLOBAL_TYPES = "Failed to generate globalTypes"; public static final String OPENECOMP_INVENTORY = "openecomp-inventory"; public static final String GLOBAL_TYPES = "globalTypes"; + static final String VFC_PARENT_PORT_ROLE = "vfc_parent_port_role"; + static final String SUB_INTERFACE_ROLE = "subinterface_role"; + static final String GROUP = "group"; + //Unified model + static final String COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX = "vm_"; + static final String COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX = "_name"; + static final String PORT_IDENTICAL_VALUE_PROPERTY_PREFIX = "port_"; + static final String SUB_INTERFACE_PROPERTY_VALUE_PREFIX = "subinterface_"; private Constants() { } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java index 54805bed2c..6b0b20ce52 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java @@ -13,12 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; - public interface FunctionTranslation { Object translateFunction(FunctionTranslator functionTranslator); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java index 257bb9bd3a..f0975cb15c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java @@ -13,27 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; +import java.util.Map; +import java.util.Optional; import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; -import java.util.Map; -import java.util.Optional; - public class FunctionTranslationFactory { + private static final Map<String, ImplementationConfiguration> functionTranslationImplMap; static { Configuration config = ConfigurationManager.lookup(); - functionTranslationImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, - ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); - functionTranslationImplMap.putAll(config.populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, - ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class)); - + functionTranslationImplMap = config + .populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); + functionTranslationImplMap.putAll(config + .populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, + ImplementationConfiguration.class)); } /** @@ -44,10 +43,8 @@ public class FunctionTranslationFactory { */ public static Optional<FunctionTranslation> getInstance(String heatFunctionKey) { if (isSupportedFunction(heatFunctionKey)) { - String functionTranslationImplClassName = - functionTranslationImplMap.get(heatFunctionKey).getImplementationClass(); - return Optional.of(CommonMethods - .newInstance(functionTranslationImplClassName, FunctionTranslation.class)); + String functionTranslationImplClassName = functionTranslationImplMap.get(heatFunctionKey).getImplementationClass(); + return Optional.of(CommonMethods.newInstance(functionTranslationImplClassName, FunctionTranslation.class)); } return Optional.empty(); } @@ -55,6 +52,4 @@ public class FunctionTranslationFactory { private static boolean isSupportedFunction(String heatFunctionKey) { return functionTranslationImplMap.containsKey(heatFunctionKey); } - } - diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaLogConstants.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaLogConstants.java index 02f4fd6226..67bf8e43c3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaLogConstants.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaLogConstants.java @@ -13,133 +13,111 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; public class HeatToToscaLogConstants { - private static final String LOG_HEAT_RESOURCE_TYPE_PREFIX = "Heat resource: '{}' with type: '{}' "; - private static final String LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX = - "therefore this resource will be ignored in TOSCA translation."; - private static final String LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX = - "therefore this connection will be ignored in TOSCA translation."; - private static final String LOG_UNSUPPORTED_PROPERTY_SUFFIX = - "therefore this property will be ignored in TOSCA translation."; - - //Contrail Attach Policy messages - public static final String LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'policy' property without 'get_attr' of 'fq_name'/'get_resource' function, " - + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_UNSUPPORTED_POLICY_RESOURCE = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include unsupported policy resource, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'network' property without 'get_resource' function, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - - //Service Instance messages - public static final String LOG_SERVICE_TEMPLATE_PROPERTY_GET_RESOURCE = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'service_template' property without 'get_resource' function, currently not supported, " - + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_SERVICE_TEMPLATE_PROPERTY_INVALID_TYPE = - "Resource id '{}' with type '{} has reference to resource '{}' with type '{}' in property service_template" - + ". Invalid type, resource type should be type of '{}', " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE = - "Resource id '{}' with type '{}' has reference to unsupported resource '{}' with type '{}' in" - + " property 'service_template', " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_MULTIPLE_SERVICE_INSTANCE_DIFF_INTERFACES = - "More than one ServiceInstance pointing to the same ServiceTemplate '{} ' with different number of " - + "interfaces., " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_MISSING_VIRTUAL_NETWORK_INTERFACE_LIST = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "missing 'virtual_network' property in 'interface_list' entry, therefore, no network connection is " - + "define for this entry."; - public static final String LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "has connection to invalid/not supported network resource, " + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; - public static final String LOG_INVALID_NETWORK_CONNECTION = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'virtual_network' property with value '{}', the connection to this network wasn't found/not " - + "supported " + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX + " for this property."; - - //Contrail v2 virtual network - public static final String LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "property network_policy_refs is referenced to an unsupported resource " - + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; - - public static final String LOG_INVALID_PROPERTY_VALUE_FORMAT = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "invalid format of property value, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - - public static final String LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "has property with invalid format of 'get_attr' function with 'fq_name' value, " - + LOG_UNSUPPORTED_PROPERTY_SUFFIX; - public static final String LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "has property with invalid format of 'get_resource' function, " - + LOG_UNSUPPORTED_PROPERTY_SUFFIX; - - //Contrail v2 vlan subinterface - public static final String LOG_MULTIPLE_INTERFACE_VALUES = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include '{}' property with more than one interface values, only the first interface will be connected, " - + "all rest will be ignored in TOSCA translation"; - public static final String LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include '{}' property which is connect to unsupported/incorrect {} resource '{}' with type '{}', " - + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; //Security rules to port public static final String LOG_UNSUPPORTED_SECURITY_RULE_PORT_CAPABILITY_CONNECTION = - "Nested resource '{}' property '{}' is pointing to resource with type '{}' which is not supported for " - + "capability '{}' connection, (security rules to port connection). Supported types are: '{}', " - + "therefore, this TOSCA capability will not be connected."; - + "Nested resource '{}' property '{}' is pointing to resource with type '{}' which is not supported for " + + "capability '{}' connection, (security rules to port connection). Supported types are: '{}', " + + "therefore, this TOSCA capability will not be connected."; //Neutron Port public static final String LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION = - "'{}' property of port resource('{}') is pointing to a resource of type '{}' which is not supported for " - + "this requirement. Supported types are: {}"; - //Volume Attachment - public static final String LOG_INVALID_INSTANCE_UUID = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'instance_uuid' property without 'get_resource' function, " - + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + "'{}' property of port resource('{}') is pointing to a resource of type '{}' which is not supported for " + + "this requirement. Supported types are: {}"; public static final String LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG = - "Volume attachment with id '{}' is pointing to unsupported resource type({}) through the property " - + "'volume_id'. The connection to the volume is ignored. Supported types are: {}"; - + "Volume attachment with id '{}' is pointing to unsupported resource type({}) through the property " + + "'volume_id'. The connection to the volume is ignored. Supported types are: {}"; //Capability/Requirement helpers - public static final String LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED = "'{}' property is not define in nested " - + "resource '{}' for the nested heat file, therefore, '{}' TOSCA {} will not be connected."; - public static final String LOG_UNSUPPORTED_CAPABILITY_CONNECTION = - "'{}' connection to '{}' capability of type '{}' is not supported/invalid," - + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; - + public static final String LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED = + "'{}' property is not define in nested " + "resource '{}' for the nested heat file, therefore, '{}' TOSCA {} will not be connected."; //Port to Net Resource Connection public static final String LOG_UNSUPPORTED_PORT_NETWORK_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not " - + "supported for requirement '{}' that connect port to network. Supported types are: '{}', " - + "therefore, this TOSCA requirement will not be connected."; - + "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not " + + "supported for requirement '{}' that connect port to network. Supported types are: '{}', " + + "therefore, this TOSCA requirement will not be connected."; public static final String LOG_UNSUPPORTED_VOL_ATTACHMENT_VOLUME_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not " - + "supported for requirement '{}' that connect VolumeAttachment to Volume. Supported " - + "types are: '{}', therefore, this TOSCA requirement will not be connected."; - + "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not " + + "supported for requirement '{}' that connect VolumeAttachment to Volume. Supported " + + "types are: '{}', therefore, this TOSCA requirement will not be connected."; //Contrail v2 vmi to net resource connection - public static final String LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES = - "Heat resource: '{}' with nested heat file: '{}' has resource '{}' with " - + "type '{}' which include 'virtual_network_refs' property with more than one network values, " - + "only the first network will be translated, all rest will be ignored in TOSCA translation."; + public static final String LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES = "Heat resource: '{}' with nested heat file: '{}' has resource '{}' with " + + "type '{}' which include 'virtual_network_refs' property with more than one network values, " + + "only the first network will be translated, all rest will be ignored in TOSCA translation."; public static final String LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not supported for " - + "requirement '{}' that connect virtual machine interface to network. Supported " - + "types are: '{}', therefore, this TOSCA requirement will not be connected."; - + "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not supported for " + + "requirement '{}' that connect virtual machine interface to network. Supported " + + "types are: '{}', therefore, this TOSCA requirement will not be connected."; //Contrail v2 vlan to interface connection public static final String LOG_UNSUPPORTED_VMI_VLAN_SUB_INTERFACE_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a {} resource with type '{}' which is not supported " - + "for requirement '{}' that connect vmi vlan sub interface to interface. Supported types are: " - + "'{}' (excluding Vlan), therefore, this TOSCA requirement will not be connected."; - + "Nested resource '{}' property '{}' is pointing to a {} resource with type '{}' which is not supported " + + "for requirement '{}' that connect vmi vlan sub interface to interface. Supported types are: " + + "'{}' (excluding Vlan), therefore, this TOSCA requirement will not be connected."; public static final String LOG_MULTIPLE_INTERFACE_VALUES_NESTED = - "Heat resource: '{}' with nested heat file: '{}' has resource '{}' with type '{}' which include '{}' " - + "property with more than one interface values, only the first interface will be connected, all " - + "rest will be ignored in TOSCA translation."; - + "Heat resource: '{}' with nested heat file: '{}' has resource '{}' with type '{}' which include '{}' " + + "property with more than one interface values, only the first interface will be connected, all " + + "rest will be ignored in TOSCA translation."; public static final String LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not supported" - + "for requirement '{}' that connect contrail port to network. Supported types " - + "are: '{}', therefore, this TOSCA requirement will not be connected."; + "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not supported" + + "for requirement '{}' that connect contrail port to network. Supported types " + + "are: '{}', therefore, this TOSCA requirement will not be connected."; + private static final String LOG_HEAT_RESOURCE_TYPE_PREFIX = "Heat resource: '{}' with type: '{}' "; + public static final String LOG_MISSING_VIRTUAL_NETWORK_INTERFACE_LIST = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "missing 'virtual_network' property in 'interface_list' entry, therefore, no network connection is " + + "define for this entry."; + //Contrail v2 vlan subinterface + public static final String LOG_MULTIPLE_INTERFACE_VALUES = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include '{}' property with more than one interface values, only the first interface will be connected, " + + "all rest will be ignored in TOSCA translation"; + private static final String LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX = "therefore this resource will be ignored in TOSCA translation."; + //Contrail Attach Policy messages + public static final String LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'policy' property without 'get_attr' of 'fq_name'/'get_resource' function, " + + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_UNSUPPORTED_POLICY_RESOURCE = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include unsupported policy resource, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'network' property without 'get_resource' function, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + //Service Instance messages + public static final String LOG_SERVICE_TEMPLATE_PROPERTY_GET_RESOURCE = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'service_template' property without 'get_resource' function, currently not supported, " + + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_SERVICE_TEMPLATE_PROPERTY_INVALID_TYPE = + "Resource id '{}' with type '{} has reference to resource '{}' with type '{}' in property service_template" + + ". Invalid type, resource type should be type of '{}', " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE = + "Resource id '{}' with type '{}' has reference to unsupported resource '{}' with type '{}' in" + " property 'service_template', " + + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_MULTIPLE_SERVICE_INSTANCE_DIFF_INTERFACES = + "More than one ServiceInstance pointing to the same ServiceTemplate '{} ' with different number of " + "interfaces., " + + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_INVALID_PROPERTY_VALUE_FORMAT = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "invalid format of property value, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + //Volume Attachment + public static final String LOG_INVALID_INSTANCE_UUID = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'instance_uuid' property without 'get_resource' function, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + private static final String LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX = "therefore this connection will be ignored in TOSCA translation."; + public static final String LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "has connection to invalid/not supported network resource, " + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; + public static final String LOG_INVALID_NETWORK_CONNECTION = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'virtual_network' property with value '{}', the connection to this network wasn't found/not " + + "supported " + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX + " for this property."; + //Contrail v2 virtual network + public static final String LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "property network_policy_refs is referenced to an unsupported resource " + + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; + public static final String LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include '{}' property which is connect to unsupported/incorrect {} resource '{}' with type '{}', " + + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; + public static final String LOG_UNSUPPORTED_CAPABILITY_CONNECTION = + "'{}' connection to '{}' capability of type '{}' is not supported/invalid," + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; + private static final String LOG_UNSUPPORTED_PROPERTY_SUFFIX = "therefore this property will be ignored in TOSCA translation."; + public static final String LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "has property with invalid format of 'get_attr' function with 'fq_name' value, " + + LOG_UNSUPPORTED_PROPERTY_SUFFIX; + public static final String LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "has property with invalid format of 'get_resource' function, " + LOG_UNSUPPORTED_PROPERTY_SUFFIX; private HeatToToscaLogConstants() { //Hiding implicit constructor diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java index d204281d6b..b7f1ff2cb9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import static org.openecomp.sdc.heat.services.HeatResourceUtil.extractNetworkRoleFromSubInterfaceId; @@ -31,7 +30,6 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.io.FilenameUtils; @@ -119,24 +117,19 @@ public class HeatToToscaUtil { */ public static TranslatorOutput loadAndTranslateTemplateData(FileContentHandler fileNameContentMap) { HeatToToscaTranslator heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface(); - try (InputStream fileContent = fileNameContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent)); } catch (IOException e) { throw new SdcRuntimeException("Failed to read manifest", e); } - fileNameContentMap.getFileList().stream().filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME))) - .forEach(fileName -> heatToToscaTranslator.addFile(fileName, - fileNameContentMap.getFileContent(fileName))); - + .forEach(fileName -> heatToToscaTranslator.addFile(fileName, fileNameContentMap.getFileContent(fileName))); Map<String, List<ErrorMessage>> errors = heatToToscaTranslator.validate(); if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { TranslatorOutput translatorOutput = new TranslatorOutput(); translatorOutput.setErrorMessages(errors); return translatorOutput; } - try (InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap)) { heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile); return heatToToscaTranslator.translate(); @@ -146,7 +139,6 @@ public class HeatToToscaUtil { } } - private static InputStream getHeatStructureTreeFile(FileContentHandler fileNameContentMap) { HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileNameContentMap); heatTreeManager.createTree(); @@ -163,8 +155,7 @@ public class HeatToToscaUtil { * @param types the types * @return the optional */ - public static Optional<List<FileData>> buildListOfFilesToSearch(String heatFileName, List<FileData> filesDataList, - FileData.Type... types) { + public static Optional<List<FileData>> buildListOfFilesToSearch(String heatFileName, List<FileData> filesDataList, FileData.Type... types) { List<FileData> list = new ArrayList<>(filesDataList); Optional<FileData> resourceFileData = HeatToToscaUtil.getFileData(heatFileName, filesDataList); if (resourceFileData.isPresent() && Objects.nonNull(resourceFileData.get().getData())) { @@ -180,8 +171,7 @@ public class HeatToToscaUtil { * @param types the types * @return the filtered list of file data by types */ - public static List<FileData> getFilteredListOfFileDataByTypes(List<FileData> filesToSearch, - FileData.Type... types) { + public static List<FileData> getFilteredListOfFileDataByTypes(List<FileData> filesToSearch, FileData.Type... types) { return filesToSearch.stream().filter(FileData.buildFileDataPredicateByType(types)).collect(Collectors.toList()); } @@ -202,8 +192,7 @@ public class HeatToToscaUtil { } /** - * Gets file data which is supported by the translator, from the context according the input heat - * file name. + * Gets file data which is supported by the translator, from the context according the input heat file name. * * @param heatFileName the heat file name * @param context the translation context @@ -212,8 +201,7 @@ public class HeatToToscaUtil { public static FileData getFileData(String heatFileName, TranslationContext context) { List<FileData> fileDataList = context.getManifest().getContent().getData(); for (FileData fileData : fileDataList) { - if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType()) && fileData.getFile() - .equals(heatFileName)) { + if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType()) && fileData.getFile().equals(heatFileName)) { return fileData; } } @@ -225,8 +213,7 @@ public class HeatToToscaUtil { Map<String, FileData> filteredFiles = filterFileDataListByType(fileDataList, typeFilter); for (FileData fileData : filteredFiles.values()) { String fileName = fileData.getFile(); - if((fileData.getType().equals(FileData.Type.HELM))) - { + if ((fileData.getType().equals(FileData.Type.HELM))) { fileDataCollection.addHelmFiles(fileData); } } @@ -234,33 +221,28 @@ public class HeatToToscaUtil { } static FileDataCollection getFileCollectionsByFilter(List<FileData> fileDataList, Set<FileData.Type> typeFilter, - TranslationContext translationContext) { + TranslationContext translationContext) { FileDataCollection fileDataCollection = new FileDataCollection(); Map<String, FileData> filteredFiles = filterFileDataListByType(fileDataList, typeFilter); Set<String> referenced = new HashSet<>(); for (FileData fileData : filteredFiles.values()) { String fileName = fileData.getFile(); - if (FileData.isHeatFile(fileData.getType())) { if (fileData.getBase() != null && fileData.getBase()) { fileDataCollection.addBaseFiles(fileData); } - HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil().yamlToObject( - translationContext.getFileContentAsStream(fileName), HeatOrchestrationTemplate.class); + HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translationContext.getFileContentAsStream(fileName), HeatOrchestrationTemplate.class); if (MapUtils.isNotEmpty(heatOrchestrationTemplate.getResources())) { - referenced.addAll(applyFilterOnFileCollection(heatOrchestrationTemplate, translationContext, - fileDataCollection, filteredFiles)); + referenced.addAll(applyFilterOnFileCollection(heatOrchestrationTemplate, translationContext, fileDataCollection, filteredFiles)); } - } else { fileDataCollection.addArtifactFiles(fileData); filteredFiles.remove(fileData.getFile()); } } - referenced.addAll(getAssociatedFiles(filteredFiles.values())); referenced.forEach(filteredFiles::remove); - if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) { for (FileData fileData : fileDataCollection.getBaseFile()) { filteredFiles.remove(fileData.getFile()); @@ -272,16 +254,13 @@ public class HeatToToscaUtil { private static Set<String> getAssociatedFiles(Collection<FileData> filteredFiles) { Set<String> associatedFiles = new HashSet<>(); - filteredFiles.stream().filter(file -> file.getParentFile() != null - && FileData.Type.canBeAssociated(file.getType())) - .forEach(file -> associatedFiles.add(file.getFile())); + filteredFiles.stream().filter(file -> file.getParentFile() != null && FileData.Type.canBeAssociated(file.getType())) + .forEach(file -> associatedFiles.add(file.getFile())); return associatedFiles; } - private static Set<String> applyFilterOnFileCollection(HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext translationContext, - FileDataCollection fileDataCollection, - Map<String, FileData> filteredFiles) { + private static Set<String> applyFilterOnFileCollection(HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext translationContext, + FileDataCollection fileDataCollection, Map<String, FileData> filteredFiles) { Set<String> nestedFiles = new HashSet<>(); List<String> filenames = extractFilenamesFromFileDataList(filteredFiles.values()); for (Resource resource : heatOrchestrationTemplate.getResources().values()) { @@ -290,24 +269,22 @@ public class HeatToToscaUtil { handleNestedFile(translationContext, fileDataCollection, filteredFiles, resourceType); nestedFiles.add(resourceType); } else if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { - Optional<String> nestedFile = handleResourceGrpNestedFile(resource, translationContext, - fileDataCollection, filteredFiles, filenames); + Optional<String> nestedFile = handleResourceGrpNestedFile(resource, translationContext, fileDataCollection, filteredFiles, filenames); nestedFile.ifPresent(nestedFiles::add); } } return nestedFiles; } - private static Optional<String> handleResourceGrpNestedFile(Resource resource, TranslationContext - translationContext, FileDataCollection fileDataCollection, - Map<String, FileData> filteredFiles, List<String> filenames) { + private static Optional<String> handleResourceGrpNestedFile(Resource resource, TranslationContext translationContext, + FileDataCollection fileDataCollection, Map<String, FileData> filteredFiles, + List<String> filenames) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); Object innerTypeDef = ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); if (innerTypeDef instanceof String) { String internalResourceType = (String) innerTypeDef; if (filenames.contains(internalResourceType)) { - handleNestedFile(translationContext, fileDataCollection, filteredFiles, - internalResourceType); + handleNestedFile(translationContext, fileDataCollection, filteredFiles, internalResourceType); return Optional.of(internalResourceType); } } @@ -315,33 +292,26 @@ public class HeatToToscaUtil { } private static void handleNestedFile(TranslationContext translationContext, FileDataCollection fileDataCollection, - Map<String, FileData> filteredFiles, - String nestedFileName) { + Map<String, FileData> filteredFiles, String nestedFileName) { fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName)); translationContext.getNestedHeatsFiles().add(nestedFileName); } - private static Map<String, FileData> filterFileDataListByType(List<FileData> fileDataList, - Set<FileData.Type> typesToGet) { + private static Map<String, FileData> filterFileDataListByType(List<FileData> fileDataList, Set<FileData.Type> typesToGet) { Map<String, FileData> filtered = new HashMap<>(); filterFileDataListByType(fileDataList, filtered, typesToGet, null); return filtered; } - private static void filterFileDataListByType(List<FileData> fileDataList, Map<String, FileData> filtered, - Set<FileData.Type> typesToGet, String parentFileName) { - fileDataList.stream().filter(file -> typesToGet.contains(file.getType())) - .forEach(file -> { - filtered.put(file.getFile(), file); - file.setParentFile(parentFileName); - }); - - Set<FileData.Type> canBeAssociatedTypes = typesToGet.stream() - .filter(FileData.Type::canBeAssociated).collect(Collectors.toSet()); - + private static void filterFileDataListByType(List<FileData> fileDataList, Map<String, FileData> filtered, Set<FileData.Type> typesToGet, + String parentFileName) { + fileDataList.stream().filter(file -> typesToGet.contains(file.getType())).forEach(file -> { + filtered.put(file.getFile(), file); + file.setParentFile(parentFileName); + }); + Set<FileData.Type> canBeAssociatedTypes = typesToGet.stream().filter(FileData.Type::canBeAssociated).collect(Collectors.toSet()); fileDataList.stream().filter(file -> Objects.nonNull(file.getData())) - .forEach(file -> filterFileDataListByType(file.getData(), filtered, - canBeAssociatedTypes, file.getFile())); + .forEach(file -> filterFileDataListByType(file.getData(), filtered, canBeAssociatedTypes, file.getFile())); } private static List<String> extractFilenamesFromFileDataList(Collection<FileData> fileDataList) { @@ -360,8 +330,8 @@ public class HeatToToscaUtil { if (propertyValue == null) { return Optional.empty(); } - return extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getContext(), propertyValue); + return extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + propertyValue); } /** @@ -373,18 +343,13 @@ public class HeatToToscaUtil { * @param propertyValue the property value * @return the optional */ - public static Optional<AttachedResourceId> extractAttachedResourceId(String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context, - Object propertyValue) { - + public static Optional<AttachedResourceId> extractAttachedResourceId(String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, Object propertyValue) { Object entity; Object translatedId = null; - if (Objects.isNull(propertyValue)) { return Optional.empty(); } - ReferenceType referenceType = ReferenceType.OTHER; if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { Map<String, Object> propMap = (Map) propertyValue; @@ -392,14 +357,11 @@ public class HeatToToscaUtil { entity = entry.getValue(); String key = entry.getKey(); referenceType = getReferenceTypeFromAttachedResouce(key); - if (FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) { - FunctionTranslator functionTranslator = new FunctionTranslator(getFunctionTranslateTo(null, null, - heatFileName, heatOrchestrationTemplate, context), null, entry.getValue(), null); - translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get() - .translateFunction(functionTranslator); - if (translatedId instanceof String - && !new FunctionTranslator().isResourceSupported((String) translatedId)) { + FunctionTranslator functionTranslator = new FunctionTranslator( + getFunctionTranslateTo(null, null, heatFileName, heatOrchestrationTemplate, context), null, entry.getValue(), null); + translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get().translateFunction(functionTranslator); + if (translatedId instanceof String && !new FunctionTranslator().isResourceSupported((String) translatedId)) { translatedId = null; } } @@ -407,7 +369,6 @@ public class HeatToToscaUtil { translatedId = propertyValue; entity = propertyValue; } - return Optional.of(new AttachedResourceId(translatedId, entity, referenceType)); } @@ -427,7 +388,6 @@ public class HeatToToscaUtil { referenceType = ReferenceType.OTHER; break; } - return referenceType; } @@ -441,11 +401,9 @@ public class HeatToToscaUtil { if (attachedResource == null) { return Optional.empty(); } - if (attachedResource.isGetResource()) { return Optional.of((String) attachedResource.getEntityId()); } - if (attachedResource.isGetAttr()) { return getResourceId(attachedResource.getEntityId()); } @@ -463,7 +421,6 @@ public class HeatToToscaUtil { if (Objects.isNull(propertyValue)) { return Optional.empty(); } - ReferenceType referenceType = ReferenceType.OTHER; if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { Map<String, Object> propMap = (Map) propertyValue; @@ -483,7 +440,6 @@ public class HeatToToscaUtil { default: break; } - } else { attachedPropertyVal = propertyValue; } @@ -522,7 +478,6 @@ public class HeatToToscaUtil { } } - /** * Is yml file type boolean. * @@ -542,16 +497,15 @@ public class HeatToToscaUtil { */ public static boolean isNestedResource(Resource resource) { String resourceType = resource.getType(); - if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); if (!(((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME) instanceof String)) { //currently only resource group which is poinitng to nested heat file is supported + //dynamic type is currently not supported return false; } - String internalResourceType = - (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); + String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); if (isYamlFile(internalResourceType)) { return true; } @@ -577,18 +531,16 @@ public class HeatToToscaUtil { } private static boolean isNestedVlanResource(String nestedHeatFileName, TranslationContext translationContext) { - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject( - translationContext.getFileContentAsStream(nestedHeatFileName), HeatOrchestrationTemplate.class); - return Objects.nonNull(nestedHeatOrchestrationTemplate.getResources()) && nestedHeatOrchestrationTemplate - .getResources().values() - .stream().anyMatch( - new ContrailV2VirtualMachineInterfaceHelper()::isVlanSubInterfaceResource); + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translationContext.getFileContentAsStream(nestedHeatFileName), HeatOrchestrationTemplate.class); + return Objects.nonNull(nestedHeatOrchestrationTemplate.getResources()) && nestedHeatOrchestrationTemplate.getResources().values().stream() + .anyMatch(new ContrailV2VirtualMachineInterfaceHelper()::isVlanSubInterfaceResource); } public static Optional<String> getSubInterfaceParentPortNodeTemplateId(TranslateTo subInterfaceTo) { String subInterfaceResourceType = getSubInterfaceResourceType(subInterfaceTo.getResource()); - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject( - subInterfaceTo.getContext().getFileContentAsStream(subInterfaceResourceType), HeatOrchestrationTemplate.class); + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(subInterfaceTo.getContext().getFileContentAsStream(subInterfaceResourceType), HeatOrchestrationTemplate.class); if (Objects.isNull(nestedHeatOrchestrationTemplate.getResources())) { return Optional.empty(); } @@ -596,14 +548,9 @@ public class HeatToToscaUtil { Resource resource = resourceEntry.getValue(); if (isVmiRefsPropertyExists(resource)) { Object toscaPropertyValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(subInterfaceTo.getServiceTemplate(), - resourceEntry.getKey(), - HeatConstants.VMI_REFS_PROPERTY_NAME, - resource.getProperties() - .get(HeatConstants.VMI_REFS_PROPERTY_NAME), - resource.getType(), subInterfaceResourceType, - nestedHeatOrchestrationTemplate, null, - subInterfaceTo.getContext()); + .getToscaPropertyValue(subInterfaceTo.getServiceTemplate(), resourceEntry.getKey(), HeatConstants.VMI_REFS_PROPERTY_NAME, + resource.getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME), resource.getType(), subInterfaceResourceType, + nestedHeatOrchestrationTemplate, null, subInterfaceTo.getContext()); return getParentNodeTemplateIdFromPropertyValue(toscaPropertyValue, subInterfaceTo); } } @@ -611,44 +558,39 @@ public class HeatToToscaUtil { } private static boolean isVmiRefsPropertyExists(Resource resource) { - return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource() - .equals(resource.getType()) - && MapUtils.isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey( - HeatConstants.VMI_REFS_PROPERTY_NAME); + return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource().equals(resource.getType()) && MapUtils + .isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey(HeatConstants.VMI_REFS_PROPERTY_NAME); } - + public static boolean isValueSpecsPropertyExists(Resource resource) { - return MapUtils.isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey( - HeatConstants.VALUE_SPECS_PROPERTY_NAME); + return MapUtils.isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey(HeatConstants.VALUE_SPECS_PROPERTY_NAME); } - - public static Optional<Object> getResourceProperty(Resource resource, String propertyName){ + + public static Optional<Object> getResourceProperty(Resource resource, String propertyName) { Map<String, Object> properties = resource.getProperties(); - if(MapUtils.isNotEmpty(properties) && properties.containsKey(propertyName)){ + if (MapUtils.isNotEmpty(properties) && properties.containsKey(propertyName)) { return Optional.ofNullable(resource.getProperties().get(propertyName)); } - return Optional.empty(); + return Optional.empty(); } public static String getSubInterfaceResourceType(Resource resource) { if (!HeatToToscaUtil.isYamlFile(resource.getType())) { - return ((Map) resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME)) - .get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME).toString(); + return ((Map) resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME)).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME) + .toString(); } return resource.getType(); } - private static Optional<String> getParentNodeTemplateIdFromPropertyValue(Object toscaPropertyValue, - TranslateTo subInterfaceTo) { + private static Optional<String> getParentNodeTemplateIdFromPropertyValue(Object toscaPropertyValue, TranslateTo subInterfaceTo) { if (toscaPropertyValue instanceof List && ((List) toscaPropertyValue).get(0) instanceof Map) { Resource subInterfaceResource = subInterfaceTo.getResource(); Map<String, String> toscaPropertyValueMap = (Map) ((List) toscaPropertyValue).get(0); String parentPortPropertyInput = toscaPropertyValueMap.get(ToscaFunctions.GET_INPUT.getFunctionName()); Map<String, Object> resourceDefPropertiesMap; if (!isYamlFile(subInterfaceResource.getType())) { - resourceDefPropertiesMap = - (Map) ((Map) subInterfaceResource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME)) - .get(HeatConstants.RESOURCE_DEF_PROPERTIES); + resourceDefPropertiesMap = (Map) ((Map) subInterfaceResource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME)) + .get(HeatConstants.RESOURCE_DEF_PROPERTIES); } else { resourceDefPropertiesMap = subInterfaceResource.getProperties(); } @@ -656,10 +598,9 @@ public class HeatToToscaUtil { if (parentPortObj instanceof Map) { Map<String, String> parentPortPropertyValue = (Map) parentPortObj; if (parentPortPropertyValue.keySet().contains(ResourceReferenceFunctions.GET_RESOURCE.getFunction())) { - return ResourceTranslationBase.getResourceTranslatedId(subInterfaceTo.getHeatFileName(), - subInterfaceTo.getHeatOrchestrationTemplate(), - parentPortPropertyValue.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()), - subInterfaceTo.getContext()); + return ResourceTranslationBase + .getResourceTranslatedId(subInterfaceTo.getHeatFileName(), subInterfaceTo.getHeatOrchestrationTemplate(), + parentPortPropertyValue.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()), subInterfaceTo.getContext()); } } } @@ -667,8 +608,7 @@ public class HeatToToscaUtil { } /** - * Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at - * least one or more compute nodes). + * Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at least one or more compute nodes). * * @param resource the resource * @param context the context @@ -676,11 +616,10 @@ public class HeatToToscaUtil { */ public static boolean isNestedVfcResource(Resource resource, TranslationContext context) { Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource); - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject( - context.getFileContentAsStream(nestedHeatFileName.get()), HeatOrchestrationTemplate.class); + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(context.getFileContentAsStream(nestedHeatFileName.get()), HeatOrchestrationTemplate.class); Map<String, Resource> resources = nestedHeatOrchestrationTemplate.getResources(); - return Objects.nonNull(resources) && resources.values().stream() - .anyMatch(ConsolidationDataUtil::isComputeResource); + return Objects.nonNull(resources) && resources.values().stream().anyMatch(ConsolidationDataUtil::isComputeResource); } /** @@ -693,13 +632,10 @@ public class HeatToToscaUtil { if (!isNestedResource(resource)) { return Optional.empty(); } - String resourceType = resource.getType(); - if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); - String internalResourceType = - (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); + String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); return Optional.of(internalResourceType); } return Optional.of(resourceType); @@ -718,8 +654,7 @@ public class HeatToToscaUtil { String resourceType = resource.getType(); if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); - String internalResourceType = - (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); + String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); return Optional.of(internalResourceType); } else { return Optional.of(resourceType); @@ -738,8 +673,7 @@ public class HeatToToscaUtil { * @param heatFileName the heat file name * @return the resource */ - public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate, String resourceId, - String heatFileName) { + public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate, String resourceId, String heatFileName) { Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); @@ -747,7 +681,6 @@ public class HeatToToscaUtil { return resource; } - /** * Get resource type. * @@ -756,8 +689,7 @@ public class HeatToToscaUtil { * @param heatFileName heat file name * @return resource type */ - public static String getResourceType(String resourceId, HeatOrchestrationTemplate heatOrchestrationTemplate, - String heatFileName) { + public static String getResourceType(String resourceId, HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName) { return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName).getType(); } @@ -799,8 +731,8 @@ public class HeatToToscaUtil { } private static Optional<String> getResourceId(Object data) { - if (data instanceof List && CollectionUtils.size(data) > 1 && FQ_NAME.equals(((List) data).get(1)) - && ((List) data).get(0) instanceof String) { + if (data instanceof List && CollectionUtils.size(data) > 1 && FQ_NAME.equals(((List) data).get(1)) && ((List) data) + .get(0) instanceof String) { return Optional.of((String) ((List) data).get(0)); } else { LOGGER.warn("invalid format of 'get_attr' function - " + data.toString()); @@ -847,15 +779,13 @@ public class HeatToToscaUtil { * @param entryDefinitionMetadata template name of the entry definition servie template * @return the tosca service model */ - private static ToscaServiceModel getToscaServiceModel(TranslationContext context, - Map<String, String> entryDefinitionMetadata) { + private static ToscaServiceModel getToscaServiceModel(TranslationContext context, Map<String, String> entryDefinitionMetadata) { Map<String, ServiceTemplate> serviceTemplates = new HashMap<>(context.getGlobalServiceTemplates()); Collection<ServiceTemplate> tmpServiceTemplates = context.getTranslatedServiceTemplates().values(); for (ServiceTemplate serviceTemplate : tmpServiceTemplates) { ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate); } - return new ToscaServiceModel(null, serviceTemplates, - ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata)); + return new ToscaServiceModel(null, serviceTemplates, ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata)); } /** @@ -865,8 +795,7 @@ public class HeatToToscaUtil { * @param context the context * @return the service template from context */ - public static Optional<ServiceTemplate> getServiceTemplateFromContext(String serviceTemplateFileName, - TranslationContext context) { + public static Optional<ServiceTemplate> getServiceTemplateFromContext(String serviceTemplateFileName, TranslationContext context) { for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) { if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) { return Optional.of(serviceTemplate); @@ -881,8 +810,7 @@ public class HeatToToscaUtil { * @param portNodeTemplate port node template * @param networkTranslatedId network node template id */ - public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate, - String networkTranslatedId) { + public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate, String networkTranslatedId) { RequirementAssignment requirement = new RequirementAssignment(); requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE); requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO); @@ -897,14 +825,12 @@ public class HeatToToscaUtil { * @param subInterfaceNodeTemplate sub interface template * @param interfaceTranslatedId interface node template id */ - public static void addBindingReqFromSubInterfaceToInterface(NodeTemplate subInterfaceNodeTemplate, - String interfaceTranslatedId) { + public static void addBindingReqFromSubInterfaceToInterface(NodeTemplate subInterfaceNodeTemplate, String interfaceTranslatedId) { RequirementAssignment requirement = new RequirementAssignment(); requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE); requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO); requirement.setNode(interfaceTranslatedId); - DataModelUtil - .addRequirementAssignment(subInterfaceNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID, requirement); + DataModelUtil.addRequirementAssignment(subInterfaceNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID, requirement); } /** @@ -936,8 +862,7 @@ public class HeatToToscaUtil { } } - public static String getToscaPropertyName(TranslationContext context, String heatResourceType, - String heatPropertyName) { + public static String getToscaPropertyName(TranslationContext context, String heatResourceType, String heatPropertyName) { return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName); } @@ -949,8 +874,7 @@ public class HeatToToscaUtil { * @return the tosca property name */ public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) { - return translateTo.getContext() - .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName); + return translateTo.getContext().getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName); } /** @@ -961,8 +885,7 @@ public class HeatToToscaUtil { * @param heatAttrName the heat attr name * @return the tosca attribute name */ - public static String getToscaAttributeName(TranslationContext context, String heatResourceType, - String heatAttrName) { + public static String getToscaAttributeName(TranslationContext context, String heatResourceType, String heatAttrName) { return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName); } @@ -974,8 +897,7 @@ public class HeatToToscaUtil { * @return the tosca attribute name */ public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) { - return translateTo.getContext() - .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName); + return translateTo.getContext().getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName); } /** @@ -992,8 +914,7 @@ public class HeatToToscaUtil { nestedSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate()); List<Map<String, Import>> globalTypesImportList = GlobalTypesGenerator.getGlobalTypesImportList(); - globalTypesImportList - .addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + globalTypesImportList.addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); nestedSubstitutionServiceTemplate.setImports(globalTypesImportList); return nestedSubstitutionServiceTemplate; } @@ -1006,8 +927,7 @@ public class HeatToToscaUtil { private static ServiceTemplate createInitGlobalSubstitutionServiceTemplate() { ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate(); Map<String, String> templateMetadata = new HashMap<>(); - templateMetadata - .put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); globalSubstitutionServiceTemplate.setMetadata(templateMetadata); globalSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList()); globalSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); @@ -1015,78 +935,8 @@ public class HeatToToscaUtil { } /** - * Create substitution node type node type. - * - * @param substitutionServiceTemplate the substitution service template - * @return the node type - */ - public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) { - NodeType substitutionNodeType = new NodeType(); - substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE); - substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription()); - substitutionNodeType.setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate)); - substitutionNodeType.setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate)); - return substitutionNodeType; - } - - private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate) { - Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>(); - Map<String, ParameterDefinition> properties = substitutionServiceTemplate.getTopology_template().getInputs(); - if (properties == null) { - return null; - } - - PropertyDefinition propertyDefinition; - String toscaPropertyName; - for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) { - toscaPropertyName = entry.getKey(); - propertyDefinition = new PropertyDefinition(); - ParameterDefinition parameterDefinition = - substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName); - propertyDefinition.setType(parameterDefinition.getType()); - propertyDefinition.setDescription(parameterDefinition.getDescription()); - propertyDefinition.setRequired(parameterDefinition.getRequired()); - propertyDefinition.set_default(parameterDefinition.get_default()); - propertyDefinition.setConstraints(parameterDefinition.getConstraints()); - propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); - propertyDefinition.setStatus(parameterDefinition.getStatus()); - substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition); - } - return substitutionNodeTypeProperties; - } - - private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(ServiceTemplate substitutionServiceTemplate) { - Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>(); - Map<String, ParameterDefinition> attributes = substitutionServiceTemplate.getTopology_template().getOutputs(); - if (attributes == null) { - return null; - } - AttributeDefinition attributeDefinition; - String toscaAttributeName; - - for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) { - attributeDefinition = new AttributeDefinition(); - toscaAttributeName = entry.getKey(); - ParameterDefinition parameterDefinition = - substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName); - if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) { - attributeDefinition.setType(parameterDefinition.getType()); - } else { - attributeDefinition.setType(PropertyType.STRING.getDisplayName()); - } - attributeDefinition.setDescription(parameterDefinition.getDescription()); - attributeDefinition.set_default(parameterDefinition.get_default()); - attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); - attributeDefinition.setStatus(parameterDefinition.getStatus()); - substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition); - } - return substitutionNodeTypeAttributes; - } - - /** - * . - * Create and add substitution mapping to the nested substitution service template, and update - * the subtitution node type accordingly with the exposed requerments and capabilities + * . Create and add substitution mapping to the nested substitution service template, and update the subtitution node type accordingly with the + * exposed requerments and capabilities * * @param context the translation context * @param substitutionNodeTypeKey the substitution node type key @@ -1094,17 +944,12 @@ public class HeatToToscaUtil { * @param substitutionNodeType the substitution node type */ public static void handleSubstitutionMapping(TranslationContext context, String substitutionNodeTypeKey, - ServiceTemplate nestedSubstitutionServiceTemplate, - NodeType substitutionNodeType) { - Map<String, Map<String, List<String>>> substitutionMapping = - getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType, nestedSubstitutionServiceTemplate, - context); + ServiceTemplate nestedSubstitutionServiceTemplate, NodeType substitutionNodeType) { + Map<String, Map<String, List<String>>> substitutionMapping = getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType, + nestedSubstitutionServiceTemplate, context); //add substitution mapping after capability and requirement expose calculation - nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings(DataModelUtil - .createSubstitutionTemplateSubMapping( - substitutionNodeTypeKey, - substitutionNodeType, - substitutionMapping)); + nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings( + DataModelUtil.createSubstitutionTemplateSubMapping(substitutionNodeTypeKey, substitutionNodeType, substitutionMapping)); } /** @@ -1115,16 +960,13 @@ public class HeatToToscaUtil { * @param context the context * @return the node type with flat hierarchy */ - public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId, ServiceTemplate serviceTemplate, - TranslationContext context) { + public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId, ServiceTemplate serviceTemplate, TranslationContext context) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - ToscaServiceModel toscaServiceModel = - HeatToToscaUtil.getToscaServiceModel(context, serviceTemplate.getMetadata()); - return (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate, - toscaServiceModel).getFlatEntity(); + ToscaServiceModel toscaServiceModel = HeatToToscaUtil.getToscaServiceModel(context, serviceTemplate.getMetadata()); + return (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate, toscaServiceModel) + .getFlatEntity(); } - /** * Create abstract substitution node template. * @@ -1133,72 +975,57 @@ public class HeatToToscaUtil { * @param substitutionNodeTypeKey the substitution node type key * @return the abstract substitute node template */ - public static NodeTemplate createAbstractSubstitutionNodeTemplate(TranslateTo translateTo, String templateName, - String substitutionNodeTypeKey) { + public static NodeTemplate createAbstractSubstitutionNodeTemplate(TranslateTo translateTo, String templateName, String substitutionNodeTypeKey) { NodeTemplate substitutionNodeTemplate = new NodeTemplate(); List<String> directiveList = new ArrayList<>(); directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); substitutionNodeTemplate.setDirectives(directiveList); substitutionNodeTemplate.setType(substitutionNodeTypeKey); - substitutionNodeTemplate.setProperties( - managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate, templateName)); + substitutionNodeTemplate.setProperties(managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate, templateName)); return substitutionNodeTemplate; } - /** - * Checks if the source and target resource is a valid candidate for adding tosca dependency - * relationship. + * Checks if the source and target resource is a valid candidate for adding tosca dependency relationship. * * @param sourceResource the source resource * @param targetResource the target resource * @param dependencyEntity the dependency entity - * @return true if the candidate resources are a valid combination for the dependency relationship - * and false otherwise + * @return true if the candidate resources are a valid combination for the dependency relationship and false otherwise */ - public static boolean isValidDependsOnCandidate(Resource sourceResource, Resource targetResource, - ConsolidationEntityType dependencyEntity, - TranslationContext context) { + public static boolean isValidDependsOnCandidate(Resource sourceResource, Resource targetResource, ConsolidationEntityType dependencyEntity, + TranslationContext context) { dependencyEntity.setEntityType(sourceResource, targetResource, context); ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType(); ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType(); - return ConsolidationTypesConnectivity.isDependsOnRelationshipValid(sourceEntityType, targetEntityType); } - private static Map<String, Object> managerSubstitutionNodeTemplateProperties(TranslateTo translateTo, - Template template, - String templateName) { + private static Map<String, Object> managerSubstitutionNodeTemplateProperties(TranslateTo translateTo, Template template, String templateName) { Map<String, Object> substitutionProperties = new HashMap<>(); Map<String, Object> heatProperties = translateTo.getResource().getProperties(); if (Objects.nonNull(heatProperties)) { for (Map.Entry<String, Object> entry : heatProperties.entrySet()) { Object property = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(translateTo.getServiceTemplate(), - translateTo.getTranslatedId(), entry.getKey(), entry.getValue(), null, - translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), template, - translateTo.getContext()); + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), entry.getKey(), entry.getValue(), null, + translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), template, translateTo.getContext()); substitutionProperties.put(entry.getKey(), property); } } return addAbstractSubstitutionProperty(templateName, substitutionProperties); } - private static Map<String, Object> addAbstractSubstitutionProperty(String templateName, - Map<String, Object> substitutionProperties) { + private static Map<String, Object> addAbstractSubstitutionProperty(String templateName, Map<String, Object> substitutionProperties) { Map<String, Object> innerProps = new HashMap<>(); - innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, - ToscaUtil.getServiceTemplateFileName(templateName)); + innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, ToscaUtil.getServiceTemplateFileName(templateName)); substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps); return substitutionProperties; } private static Map<String, Map<String, List<String>>> getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType, - ServiceTemplate substitutionServiceTemplate, - TranslationContext context) { - Map<String, NodeTemplate> nodeTemplates = - substitutionServiceTemplate.getTopology_template().getNode_templates(); + ServiceTemplate substitutionServiceTemplate, + TranslationContext context) { + Map<String, NodeTemplate> nodeTemplates = substitutionServiceTemplate.getTopology_template().getNode_templates(); String nodeTemplateId; NodeTemplate nodeTemplate; String nodeType; @@ -1206,7 +1033,6 @@ public class HeatToToscaUtil { if (nodeTemplates == null) { return substitutionMapping; } - Map<String, List<String>> capabilitySubstitutionMapping = new HashMap<>(); Map<String, List<String>> requirementSubstitutionMapping = new HashMap<>(); substitutionMapping.put("capability", capabilitySubstitutionMapping); @@ -1218,54 +1044,43 @@ public class HeatToToscaUtil { Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>(); Map<String, CapabilityDefinition> exposedCapabilitiesDefinition; ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) { nodeTemplateId = entry.getKey(); nodeTemplate = entry.getValue(); nodeType = nodeTemplate.getType(); - // get requirements - nodeTypeRequirementsDefinition = getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate, - requirementSubstitutionMapping, context); + nodeTypeRequirementsDefinition = getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate, requirementSubstitutionMapping, + context); nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate); fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment); //set substitution node type requirements exposedRequirementsDefinition = toscaAnalyzerService - .calculateExposedRequirements(nodeTypeRequirementsDefinition, - nodeTemplateRequirementsAssignment); - DataModelUtil.addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition, - nodeTemplateId); - + .calculateExposedRequirements(nodeTypeRequirementsDefinition, nodeTemplateRequirementsAssignment); + DataModelUtil.addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition, nodeTemplateId); //get capabilities - addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, nodeType, - nodeTemplateId, substitutionServiceTemplate, context); + addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, nodeType, nodeTemplateId, + substitutionServiceTemplate, context); } - exposedCapabilitiesDefinition = toscaAnalyzerService - .calculateExposedCapabilities(nodeTypeCapabilitiesDefinition, - fullFilledRequirementsDefinition); + .calculateExposedCapabilities(nodeTypeCapabilitiesDefinition, fullFilledRequirementsDefinition); DataModelUtil.setNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition); return substitutionMapping; } private static void addNodeTypeCapabilitiesToSubMapping(Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition, - Map<String, List<String>> capabilitySubstitutionMapping, - String type, String templateName, - ServiceTemplate serviceTemplate, - TranslationContext context) { + Map<String, List<String>> capabilitySubstitutionMapping, String type, String templateName, + ServiceTemplate serviceTemplate, TranslationContext context) { NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context); - if (flatNodeType.getCapabilities() != null) { flatNodeType.getCapabilities().entrySet().stream().forEach( - capabilityNodeEntry -> addCapabilityToSubMapping(templateName, capabilityNodeEntry, - nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping)); + capabilityNodeEntry -> addCapabilityToSubMapping(templateName, capabilityNodeEntry, nodeTypeCapabilitiesDefinition, + capabilitySubstitutionMapping)); } } - private static void addCapabilityToSubMapping(String templateName, - Map.Entry<String, CapabilityDefinition> capabilityNodeEntry, - Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition, - Map<String, List<String>> capabilitySubstitutionMapping) { + private static void addCapabilityToSubMapping(String templateName, Map.Entry<String, CapabilityDefinition> capabilityNodeEntry, + Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition, + Map<String, List<String>> capabilitySubstitutionMapping) { String capabilityKey; List<String> capabilityMapping; capabilityKey = capabilityNodeEntry.getKey() + UNDERSCORE + templateName; @@ -1276,26 +1091,22 @@ public class HeatToToscaUtil { capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping); } - private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(String type, String templateName, - ServiceTemplate serviceTemplate, - Map<String, List<String>> requirementSubstitutionMapping, - TranslationContext context) { + private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(String type, String templateName, ServiceTemplate serviceTemplate, + Map<String, List<String>> requirementSubstitutionMapping, + TranslationContext context) { List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>(); NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context); List<String> requirementMapping; - if (flatNodeType.getRequirements() == null) { return requirementList; } - for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) { for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap.entrySet()) { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil.yamlToObject( - toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()), - RequirementDefinition.class); + RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()), RequirementDefinition.class); if (Objects.isNull(requirementNodeEntryValue.getOccurrences())) { - requirementNodeEntryValue.setOccurrences(new Object[] {1, 1}); + requirementNodeEntryValue.setOccurrences(new Object[]{1, 1}); } Map<String, RequirementDefinition> requirementDef = new HashMap<>(); requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue); @@ -1303,10 +1114,9 @@ public class HeatToToscaUtil { requirementMapping = new ArrayList<>(); requirementMapping.add(templateName); requirementMapping.add(requirementNodeEntry.getKey()); - requirementSubstitutionMapping - .put(requirementNodeEntry.getKey() + UNDERSCORE + templateName, requirementMapping); + requirementSubstitutionMapping.put(requirementNodeEntry.getKey() + UNDERSCORE + templateName, requirementMapping); if (Objects.isNull(requirementNodeEntryValue.getNode())) { - requirementNodeEntryValue.setOccurrences(new Object[] {1, 1}); + requirementNodeEntryValue.setOccurrences(new Object[]{1, 1}); } } } @@ -1320,21 +1130,17 @@ public class HeatToToscaUtil { * @param context the context * @return the service template */ - public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(ServiceTemplate serviceTemplate, - TranslationContext context) { - ServiceTemplate globalSubstitutionServiceTemplate = - context.getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(ServiceTemplate serviceTemplate, TranslationContext context) { + ServiceTemplate globalSubstitutionServiceTemplate = context.getTranslatedServiceTemplates() + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); if (globalSubstitutionServiceTemplate == null) { globalSubstitutionServiceTemplate = HeatToToscaUtil.createInitGlobalSubstitutionServiceTemplate(); - context.getTranslatedServiceTemplates() - .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate); + context.getTranslatedServiceTemplates().put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate); } boolean isImportAddedToServiceTemplate = DataModelUtil - .isImportAddedToServiceTemplate(serviceTemplate.getImports(), - Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + .isImportAddedToServiceTemplate(serviceTemplate.getImports(), Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); if (!isImportAddedToServiceTemplate) { - serviceTemplate.getImports() - .addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + serviceTemplate.getImports().addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); } return globalSubstitutionServiceTemplate; } @@ -1371,33 +1177,28 @@ public class HeatToToscaUtil { return serviceTemplateImport; } - public static ToscaServiceModel createToscaServiceModel(ServiceTemplate entryDefinitionServiceTemplate, - TranslationContext translationContext) { + public static ToscaServiceModel createToscaServiceModel(ServiceTemplate entryDefinitionServiceTemplate, TranslationContext translationContext) { return new ToscaServiceModel(getCsarArtifactFiles(translationContext), getServiceTemplates(translationContext), - ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate)); + ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate)); } private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) { FileContentHandler artifactFiles = new FileContentHandler(); artifactFiles.addAll(translationContext.getFiles()); artifactFiles.addAll(translationContext.getExternalArtifacts()); - HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles()); heatTreeManager.createTree(); ValidationStructureList validationStructureList = new ValidationStructureList(heatTreeManager.getTree()); - byte[] validationStructureFile = - FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON); + byte[] validationStructureFile = FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON); artifactFiles.addFile("HEAT.meta", validationStructureFile); return artifactFiles; } - private static Map<String, ServiceTemplate> getServiceTemplates(TranslationContext translationContext) { List<ServiceTemplate> serviceTemplates = new ArrayList<>(); serviceTemplates.addAll(GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP).values()); serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values()); Map<String, ServiceTemplate> serviceTemplatesMap = new HashMap<>(); - for (ServiceTemplate template : serviceTemplates) { serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template); } @@ -1405,8 +1206,7 @@ public class HeatToToscaUtil { } public static String getNestedResourceTypePrefix(TranslateTo translateTo) { - if (isSubInterfaceResource(translateTo.getResource(), translateTo.getContext()) && isSubInterfaceBoundToPort( - translateTo)) { + if (isSubInterfaceResource(translateTo.getResource(), translateTo.getContext()) && isSubInterfaceBoundToPort(translateTo)) { return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX; } return ToscaNodeType.NESTED_HEAT_RESOURCE_TYPE_PREFIX; @@ -1416,36 +1216,91 @@ public class HeatToToscaUtil { return HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(translateTo).isPresent(); } - //Method evaluate the network role from sub interface node template id, designed considering // only single sub interface present in nested file else it will return null - public static Optional<String> getNetworkRoleFromSubInterfaceId(Resource resource, - TranslationContext translationContext) { + public static Optional<String> getNetworkRoleFromSubInterfaceId(Resource resource, TranslationContext translationContext) { Optional<String> networkRole = Optional.empty(); Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource); - if (!nestedHeatFileName.isPresent()) { return networkRole; } - - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject( - translationContext.getFileContentAsStream(nestedHeatFileName.get()), HeatOrchestrationTemplate.class); - + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translationContext.getFileContentAsStream(nestedHeatFileName.get()), HeatOrchestrationTemplate.class); if (MapUtils.isNotEmpty(nestedHeatOrchestrationTemplate.getResources())) { - ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper = - new ContrailV2VirtualMachineInterfaceHelper(); - Optional<Map.Entry<String, Resource>> vlanSubInterfaceResource = - nestedHeatOrchestrationTemplate.getResources().entrySet().stream() - .filter(resourceEntry -> contrailV2VirtualMachineInterfaceHelper - .isVlanSubInterfaceResource( - resourceEntry.getValue())) - .findFirst(); + ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper = new ContrailV2VirtualMachineInterfaceHelper(); + Optional<Map.Entry<String, Resource>> vlanSubInterfaceResource = nestedHeatOrchestrationTemplate.getResources().entrySet().stream() + .filter(resourceEntry -> contrailV2VirtualMachineInterfaceHelper.isVlanSubInterfaceResource(resourceEntry.getValue())).findFirst(); if (vlanSubInterfaceResource.isPresent()) { Map.Entry<String, Resource> vlanSubInterfaceResourceEntry = vlanSubInterfaceResource.get(); networkRole = extractNetworkRoleFromSubInterfaceId(vlanSubInterfaceResourceEntry.getKey(), - vlanSubInterfaceResourceEntry.getValue().getType()); + vlanSubInterfaceResourceEntry.getValue().getType()); } } return networkRole; } + /** + * Create substitution node type node type. + * + * @param substitutionServiceTemplate the substitution service template + * @return the node type + */ + public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) { + NodeType substitutionNodeType = new NodeType(); + substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE); + substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription()); + substitutionNodeType.setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate)); + substitutionNodeType.setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate)); + return substitutionNodeType; + } + + private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate) { + Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>(); + Map<String, ParameterDefinition> properties = substitutionServiceTemplate.getTopology_template().getInputs(); + if (properties == null) { + return null; + } + PropertyDefinition propertyDefinition; + String toscaPropertyName; + for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) { + toscaPropertyName = entry.getKey(); + propertyDefinition = new PropertyDefinition(); + ParameterDefinition parameterDefinition = substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName); + propertyDefinition.setType(parameterDefinition.getType()); + propertyDefinition.setDescription(parameterDefinition.getDescription()); + propertyDefinition.setRequired(parameterDefinition.getRequired()); + propertyDefinition.set_default(parameterDefinition.get_default()); + propertyDefinition.setConstraints(parameterDefinition.getConstraints()); + propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); + propertyDefinition.setStatus(parameterDefinition.getStatus()); + substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition); + } + return substitutionNodeTypeProperties; + } + //Method evaluate the network role from sub interface node template id, designed considering + + private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(ServiceTemplate substitutionServiceTemplate) { + Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>(); + Map<String, ParameterDefinition> attributes = substitutionServiceTemplate.getTopology_template().getOutputs(); + if (attributes == null) { + return null; + } + AttributeDefinition attributeDefinition; + String toscaAttributeName; + for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) { + attributeDefinition = new AttributeDefinition(); + toscaAttributeName = entry.getKey(); + ParameterDefinition parameterDefinition = substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName); + if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) { + attributeDefinition.setType(parameterDefinition.getType()); + } else { + attributeDefinition.setType(PropertyType.STRING.getDisplayName()); + } + attributeDefinition.setDescription(parameterDefinition.getDescription()); + attributeDefinition.set_default(parameterDefinition.get_default()); + attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); + attributeDefinition.setStatus(parameterDefinition.getStatus()); + substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition); + } + return substitutionNodeTypeAttributes; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java index e732080cb5..a54c85ff82 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; import org.openecomp.sdc.heat.datatypes.model.Resource; public interface NameExtractor { - String extractNodeTypeName(Resource resource, String resourceId, String translatedId); - + String extractNodeTypeName(Resource resource, String resourceId, String translatedId); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java index b4d41f5b6c..abd19863d5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,58 +17,51 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; -import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; - import java.util.List; import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; +import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; public class NameExtractorUtil { - /** - * Extract Node Type Name By Properties Priority. - * @param properties properties list - * @param propertiesRegexMatchers Regex expression list - * @return node type name - */ - public static Optional<String> extractNodeTypeNameByPropertiesPriority( - Map<String, Object> properties, - List<PropertyRegexMatcher> propertiesRegexMatchers) { - - for (PropertyRegexMatcher propertyRegexMatcher : propertiesRegexMatchers) { - Optional<String> parameterNameValue = - HeatToToscaUtil.getPropertyParameterNameValue( - properties.get(propertyRegexMatcher.getPropertyName())); - if (parameterNameValue.isPresent()) { - if (isPropertyValueMatchNamingConvention(propertyRegexMatcher, parameterNameValue.get())) { - return Optional.of(parameterNameValue.get().substring(0, parameterNameValue.get() - .lastIndexOf(propertyRegexMatcher.getStringToSearchForPropertyValue()))); + /** + * Extract Node Type Name By Properties Priority. + * + * @param properties properties list + * @param propertiesRegexMatchers Regex expression list + * @return node type name + */ + public static Optional<String> extractNodeTypeNameByPropertiesPriority(Map<String, Object> properties, + List<PropertyRegexMatcher> propertiesRegexMatchers) { + for (PropertyRegexMatcher propertyRegexMatcher : propertiesRegexMatchers) { + Optional<String> parameterNameValue = HeatToToscaUtil + .getPropertyParameterNameValue(properties.get(propertyRegexMatcher.getPropertyName())); + if (parameterNameValue.isPresent()) { + if (isPropertyValueMatchNamingConvention(propertyRegexMatcher, parameterNameValue.get())) { + return Optional.of(parameterNameValue.get() + .substring(0, parameterNameValue.get().lastIndexOf(propertyRegexMatcher.getStringToSearchForPropertyValue()))); + } + } } - } + return Optional.empty(); } - return Optional.empty(); - } - /** - * Check if property value match the naming convention using Regex expression. - * @param propertyRegexMatcher naming convention using Regex expression - * @param propertyValue property value - * @return true is there is a match, false otherwise - */ - public static boolean isPropertyValueMatchNamingConvention(PropertyRegexMatcher - propertyRegexMatcher, - String propertyValue) { - for (Pattern pattern : propertyRegexMatcher.getRegexPatterns()) { - if (pattern.matcher(propertyValue).matches()) { - return true; - } + /** + * Check if property value match the naming convention using Regex expression. + * + * @param propertyRegexMatcher naming convention using Regex expression + * @param propertyValue property value + * @return true is there is a match, false otherwise + */ + public static boolean isPropertyValueMatchNamingConvention(PropertyRegexMatcher propertyRegexMatcher, String propertyValue) { + for (Pattern pattern : propertyRegexMatcher.getRegexPatterns()) { + if (pattern.matcher(propertyValue).matches()) { + return true; + } + } + return false; } - return false; - } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java index 6537e95eeb..158d5ed60e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; - +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; -import java.util.Optional; - - public interface ResourceTranslation { - //return the Id of translated object (NodeTemplate, RelationshipTemplate and etc) - Optional<String> translateResource(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Resource resource, String resourceId, - TranslationContext context); + //return the Id of translated object (NodeTemplate, RelationshipTemplate and etc) + Optional<String> translateResource(String heatFileName, ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + Resource resource, String resourceId, TranslationContext context); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java index d5157debce..50607b9b35 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; - +import java.util.Map; import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; import org.openecomp.core.utilities.CommonMethods; @@ -28,49 +27,43 @@ import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; -import java.util.Map; - - public class ResourceTranslationFactory { - private static Map<String, ImplementationConfiguration> resourceTranslationImplMap; - static { - Configuration config = ConfigurationManager.lookup(); - resourceTranslationImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, - ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); - resourceTranslationImplMap.putAll(config.populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, - ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class)); - } + private static Map<String, ImplementationConfiguration> resourceTranslationImplMap; - /** - * Gets resource translation instance. - * - * @param resource the resource - * @return the instance - */ - public static ResourceTranslationBase getInstance(Resource resource) { - if (isSupportedResource(resource.getType())) { - return getResourceTranslationImpl(resource.getType()); - } else if (HeatToToscaUtil.isYmlFileType(resource.getType())) { - return getResourceTranslationImpl(ConfigConstants.NESTED_RESOURCE_TRANSLATION_IMPL_KEY); + static { + Configuration config = ConfigurationManager.lookup(); + resourceTranslationImplMap = config + .populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); + resourceTranslationImplMap.putAll(config + .populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, + ImplementationConfiguration.class)); } - return getResourceTranslationImpl(ConfigConstants.DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY); - } - private static ResourceTranslationBase getResourceTranslationImpl(String resourceImplKey) { - String resourceTranslationImplClassName = resourceTranslationImplMap - .get(resourceImplKey).getImplementationClass(); - return CommonMethods - .newInstance(resourceTranslationImplClassName, ResourceTranslationBase.class); - } + /** + * Gets resource translation instance. + * + * @param resource the resource + * @return the instance + */ + public static ResourceTranslationBase getInstance(Resource resource) { + if (isSupportedResource(resource.getType())) { + return getResourceTranslationImpl(resource.getType()); + } else if (HeatToToscaUtil.isYmlFileType(resource.getType())) { + return getResourceTranslationImpl(ConfigConstants.NESTED_RESOURCE_TRANSLATION_IMPL_KEY); + } + return getResourceTranslationImpl(ConfigConstants.DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY); + } - private static boolean isSupportedResource(String resourceType) { - if (resourceTranslationImplMap.containsKey(resourceType) - && resourceTranslationImplMap.get(resourceType).isEnable()) { - return true; + private static ResourceTranslationBase getResourceTranslationImpl(String resourceImplKey) { + String resourceTranslationImplClassName = resourceTranslationImplMap.get(resourceImplKey).getImplementationClass(); + return CommonMethods.newInstance(resourceTranslationImplClassName, ResourceTranslationBase.class); } - return false; - } + private static boolean isSupportedResource(String resourceType) { + if (resourceTranslationImplMap.containsKey(resourceType) && resourceTranslationImplMap.get(resourceType).isEnable()) { + return true; + } + return false; + } } - diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java index 6d22a3602c..0547ec730b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import java.util.ArrayList; @@ -24,10 +23,13 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; -import org.onap.sdc.tosca.datatypes.model.*; +import org.onap.sdc.tosca.datatypes.model.GroupDefinition; +import org.onap.sdc.tosca.datatypes.model.ParameterDefinition; +import org.onap.sdc.tosca.datatypes.model.PropertyType; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; +import org.onap.sdc.tosca.datatypes.model.TopologyTemplate; import org.onap.sdc.tosca.datatypes.model.heatextend.ParameterDefinitionExt; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.core.translator.datatypes.TranslatorOutput; @@ -85,14 +87,13 @@ public class TranslationService { public TranslatorOutput translateHeatFiles(TranslationContext translationContext) { ServiceTemplate mainServiceTemplate = createMainServiceTemplate(translationContext); List<FileData> fileDataList = translationContext.getManifest().getContent().getData(); - FileDataCollection fileDataCollection = HeatToToscaUtil.getFileCollectionsByFilter(fileDataList, - TranslationService.getTypesToProcessByTranslator(), translationContext); - FileDataCollection fileDataCollectionHelm = HeatToToscaUtil.getFileCollectionsByHelmFilter(fileDataList, - TranslationService.getTypesToProcessByHelmTranslator()); - + FileDataCollection fileDataCollection = HeatToToscaUtil + .getFileCollectionsByFilter(fileDataList, TranslationService.getTypesToProcessByTranslator(), translationContext); + FileDataCollection fileDataCollectionHelm = HeatToToscaUtil + .getFileCollectionsByHelmFilter(fileDataList, TranslationService.getTypesToProcessByHelmTranslator()); if (fileDataCollection.getBaseFile() != null) { for (FileData fileData : fileDataCollection.getBaseFile()) { - translateHeatFile(mainServiceTemplate, fileData, translationContext); + translateHeatFile(mainServiceTemplate, fileData, translationContext); } } if (fileDataCollection.getAddOnFiles() != null) { @@ -100,30 +101,24 @@ public class TranslationService { translateHeatFile(mainServiceTemplate, fileData, translationContext); } } - - if (fileDataCollectionHelm.getHelmFile() !=null) { + if (fileDataCollectionHelm.getHelmFile() != null) { for (FileData fileData : fileDataCollectionHelm.getHelmFile()) { translateHelmFile(mainServiceTemplate, fileData, translationContext); - } } - - ToscaServiceModel toscaServiceModel = - HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); - + ToscaServiceModel toscaServiceModel = HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); TranslatorOutput translatorOutput = new TranslatorOutput(); //Keeping a copy of tosca service model after first stage of translation for extraction of + // composition data - translatorOutput.setNonUnifiedToscaServiceModel( - ToscaServiceModel.getClonedServiceModel(toscaServiceModel)); + translatorOutput.setNonUnifiedToscaServiceModel(ToscaServiceModel.getClonedServiceModel(toscaServiceModel)); translatorOutput.setToscaServiceModel(toscaServiceModel); return translatorOutput; } private ServiceTemplate createMainServiceTemplate(TranslationContext translationContext) { ServiceTemplate mainServiceTemplate = new ServiceTemplate(); - translationContext.getTranslatedServiceTemplates() - .put(Constants.MAIN_TEMPLATE_NAME, mainServiceTemplate); + translationContext.getTranslatedServiceTemplates().put(Constants.MAIN_TEMPLATE_NAME, mainServiceTemplate); Map<String, String> templateMetadata = new HashMap<>(); templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME); mainServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); @@ -140,50 +135,37 @@ public class TranslationService { * @param heatFileData the heat file data * @param context the context */ - public void translateHeatFile(ServiceTemplate serviceTemplate, FileData heatFileData, - TranslationContext context) { + public void translateHeatFile(ServiceTemplate serviceTemplate, FileData heatFileData, TranslationContext context) { String heatFileName = heatFileData.getFile(); HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() - .yamlToObject(context.getFileContentAsStream(heatFileName), HeatOrchestrationTemplate.class); - - translateInputParameters(serviceTemplate, heatOrchestrationTemplate, heatFileData, context, - heatFileName); - + .yamlToObject(context.getFileContentAsStream(heatFileName), HeatOrchestrationTemplate.class); + translateInputParameters(serviceTemplate, heatOrchestrationTemplate, heatFileData, context, heatFileName); translateResources(heatFileName, serviceTemplate, heatOrchestrationTemplate, context); - translateOutputParameters(serviceTemplate, heatOrchestrationTemplate, heatFileData, - heatFileName, context); + translateOutputParameters(serviceTemplate, heatOrchestrationTemplate, heatFileData, heatFileName, context); createHeatStackGroup(serviceTemplate, heatFileData, heatOrchestrationTemplate, context); handleHeatPseudoParam(heatFileName, serviceTemplate, context); if (Objects.nonNull(heatFileData.getData())) { heatFileData.getData().stream().filter(data -> FileData.Type.canBeAssociated(data.getType())) - .forEach(data -> translateHeatFile(serviceTemplate, data, context)); + .forEach(data -> translateHeatFile(serviceTemplate, data, context)); } } - - public void translateHelmFile(ServiceTemplate serviceTemplate, FileData heatFileData, - TranslationContext context) { + public void translateHelmFile(ServiceTemplate serviceTemplate, FileData heatFileData, TranslationContext context) { String heatFileName = heatFileData.getFile(); Map<String, ParameterDefinition> inputs = serviceTemplate.getTopology_template().getInputs(); if (!Objects.isNull(inputs)) { - - inputs.entrySet().forEach( - stringParameterDefinitionEntry -> { - List inputParamVFModuleList = getVFModulesList( - inputs.get(stringParameterDefinitionEntry.getKey())); - if (!inputParamVFModuleList.contains(FileUtils.getFileWithoutExtention(heatFileName)) ){ - inputParamVFModuleList.add(FileUtils.getFileWithoutExtention(heatFileName)); - } - } - ); + inputs.entrySet().forEach(stringParameterDefinitionEntry -> { + List inputParamVFModuleList = getVFModulesList(inputs.get(stringParameterDefinitionEntry.getKey())); + if (!inputParamVFModuleList.contains(FileUtils.getFileWithoutExtention(heatFileName))) { + inputParamVFModuleList.add(FileUtils.getFileWithoutExtention(heatFileName)); + } + }); } inputs.putAll(inputs); } - private void handleHeatPseudoParam(String heatFileName, ServiceTemplate serviceTemplate, - TranslationContext context) { - Map<String, String> translatedHeatPseudoParam = - context.getUsedHeatPseudoParams().get(heatFileName); + private void handleHeatPseudoParam(String heatFileName, ServiceTemplate serviceTemplate, TranslationContext context) { + Map<String, String> translatedHeatPseudoParam = context.getUsedHeatPseudoParams().get(heatFileName); if (Objects.nonNull(translatedHeatPseudoParam)) { for (String heatPseudoParam : translatedHeatPseudoParam.keySet()) { if (!serviceTemplate.getTopology_template().getInputs().containsKey(heatPseudoParam)) { @@ -191,54 +173,41 @@ public class TranslationService { parameterDefinition.setType(PropertyType.STRING.getDisplayName()); parameterDefinition.setRequired(false); String parameterDefinitionId = translatedHeatPseudoParam.get(heatPseudoParam); - DataModelUtil.addInputParameterToTopologyTemplate(serviceTemplate, parameterDefinitionId, - parameterDefinition); + DataModelUtil.addInputParameterToTopologyTemplate(serviceTemplate, parameterDefinitionId, parameterDefinition); } } } } - private void createHeatStackGroup(ServiceTemplate serviceTemplate, FileData heatFileData, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private void createHeatStackGroup(ServiceTemplate serviceTemplate, FileData heatFileData, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl(); final String fileName = heatFileData.getFile(); final String heatStackGroupId = FileUtils.getFileWithoutExtention(fileName) + "_group"; - GroupDefinition groupDefinition = new GroupDefinition(); groupDefinition.setType(ToscaGroupType.HEAT_STACK); groupDefinition.setProperties(new HashMap<>()); - groupDefinition.getProperties() - .put("heat_file", "../" + toscaFileOutputService.getArtifactsFolderName() + "/" + fileName); + groupDefinition.getProperties().put("heat_file", "../" + toscaFileOutputService.getArtifactsFolderName() + "/" + fileName); String hotDescription = heatOrchestrationTemplate.getDescription(); if (hotDescription != null && !hotDescription.isEmpty()) { groupDefinition.getProperties().put(Constants.DESCRIPTION_PROPERTY_NAME, hotDescription); } groupDefinition.setMembers(new ArrayList<>()); - Set<String> heatStackGroupMembersIds = getHeatStackGroupMembers(fileName, - serviceTemplate, context); + Set<String> heatStackGroupMembersIds = getHeatStackGroupMembers(fileName, serviceTemplate, context); if (CollectionUtils.isEmpty(heatStackGroupMembersIds)) { return; //not creating a group when no resources are present in the heat input } groupDefinition.getMembers().addAll(heatStackGroupMembersIds); - DataModelUtil - .addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupId, groupDefinition); + DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupId, groupDefinition); } - private Set<String> getHeatStackGroupMembers(String heatFileName, - ServiceTemplate serviceTemplate, - TranslationContext context) { - + private Set<String> getHeatStackGroupMembers(String heatFileName, ServiceTemplate serviceTemplate, TranslationContext context) { Map<String, Set<String>> heatStackGroupMembers = context.getHeatStackGroupMembers(); - Set<String> groupMembers = MapUtils.isEmpty(heatStackGroupMembers) ? new HashSet<>() - : heatStackGroupMembers.get(heatFileName); - + Set<String> groupMembers = MapUtils.isEmpty(heatStackGroupMembers) ? new HashSet<>() : heatStackGroupMembers.get(heatFileName); if (CollectionUtils.isEmpty(groupMembers)) { return new HashSet<>(); } - Set<String> updatedMembersIds = new HashSet<>(); - groupMembers.forEach(member -> { if (Objects.nonNull(DataModelUtil.getNodeTemplate(serviceTemplate, member))) { updatedMembersIds.add(member); @@ -246,33 +215,24 @@ public class TranslationService { updateSubstitutableGroupMemberId(heatFileName, serviceTemplate, updatedMembersIds); } }); - return updatedMembersIds; } - private void updateSubstitutableGroupMemberId(String heatFileName, - ServiceTemplate serviceTemplate, - Set<String> updatedMembersIds) { - Optional<String> substitutableGroupMemberId = - ToscaUtil.getSubstitutableGroupMemberId(heatFileName, serviceTemplate); - + private void updateSubstitutableGroupMemberId(String heatFileName, ServiceTemplate serviceTemplate, Set<String> updatedMembersIds) { + Optional<String> substitutableGroupMemberId = ToscaUtil.getSubstitutableGroupMemberId(heatFileName, serviceTemplate); substitutableGroupMemberId.ifPresent(updatedMembersIds::add); } - private void translateInputParameters(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - FileData heatFileData, TranslationContext context, - String heatFileName) { + private void translateInputParameters(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, FileData heatFileData, + TranslationContext context, String heatFileName) { if (heatOrchestrationTemplate.getParameters() == null) { return; } - final Environment heatEnvFile = getHeatEnvFile(heatFileData, context); final Map<String, Object> parameters = heatEnvFile.getParameters(); - Map<String, ParameterDefinition> parameterDefinitionMap = - TranslatorHeatToToscaParameterConverter - .parameterConverter(serviceTemplate, heatOrchestrationTemplate.getParameters(), - heatOrchestrationTemplate, heatFileName, heatFileData.getParentFile(), context, parameters); + Map<String, ParameterDefinition> parameterDefinitionMap = TranslatorHeatToToscaParameterConverter + .parameterConverter(serviceTemplate, heatOrchestrationTemplate.getParameters(), heatOrchestrationTemplate, heatFileName, + heatFileData.getParentFile(), context, parameters); Object parameterValue; if (parameters != null) { for (Map.Entry<String, ParameterDefinition> entry : parameterDefinitionMap.entrySet()) { @@ -280,45 +240,35 @@ public class TranslationService { parameterValue = parameters.get(paramName); if (parameterValue != null) { entry.getValue().set_default(TranslatorHeatToToscaParameterConverter - .getToscaParameterDefaultValue(null, null, parameterValue, entry.getValue().getType(), - heatFileName, heatOrchestrationTemplate, context)); + .getToscaParameterDefaultValue(null, null, parameterValue, entry.getValue().getType(), heatFileName, + heatOrchestrationTemplate, context)); } } } - - Map<String, ParameterDefinition> inputs = serviceTemplate.getTopology_template().getInputs(); if (Objects.isNull(inputs)) { serviceTemplate.getTopology_template().setInputs(parameterDefinitionMap); } else { setInputs(inputs, parameterDefinitionMap); - } - } private void setInputs(Map<String, ParameterDefinition> inputs, Map<String, ParameterDefinition> newParameters) { - updateAnnotations(inputs, newParameters); inputs.putAll(newParameters); - } - private void updateAnnotations(Map<String, ParameterDefinition> inputParameters, Map<String, - ParameterDefinition> newParameters) { - newParameters.entrySet().stream().filter(stringParameterDefinitionEntry -> - inputParameters.containsKey(stringParameterDefinitionEntry.getKey()) - && isHasAnnotation(inputParameters, stringParameterDefinitionEntry)) - .forEach(stringParameterDefinitionEntry -> { - List inputParamVFModuleList = getVFModulesList( - inputParameters.get(stringParameterDefinitionEntry.getKey())); - List newParamVFModuleList = getVFModulesList(stringParameterDefinitionEntry.getValue()); - if (inputParamVFModuleList.contains(newParamVFModuleList.get(0))) { - newParamVFModuleList.remove(0); - } - newParamVFModuleList.addAll(inputParamVFModuleList); - }); - + private void updateAnnotations(Map<String, ParameterDefinition> inputParameters, Map<String, ParameterDefinition> newParameters) { + newParameters.entrySet().stream().filter( + stringParameterDefinitionEntry -> inputParameters.containsKey(stringParameterDefinitionEntry.getKey()) && isHasAnnotation(inputParameters, + stringParameterDefinitionEntry)).forEach(stringParameterDefinitionEntry -> { + List inputParamVFModuleList = getVFModulesList(inputParameters.get(stringParameterDefinitionEntry.getKey())); + List newParamVFModuleList = getVFModulesList(stringParameterDefinitionEntry.getValue()); + if (inputParamVFModuleList.contains(newParamVFModuleList.get(0))) { + newParamVFModuleList.remove(0); + } + newParamVFModuleList.addAll(inputParamVFModuleList); + }); } private boolean isHasAnnotation(Map<String, ParameterDefinition> inputParameters, Map.Entry<String, ParameterDefinition> newParameterSet) { @@ -329,91 +279,74 @@ public class TranslationService { private List getVFModulesList(ParameterDefinition param) { ParameterDefinitionExt parameterDefinitionExt = (ParameterDefinitionExt) param; - return (List) parameterDefinitionExt.getAnnotations().get(ToscaConstants.SOURCE_ANNOTATION_ID).getProperties(). - get(ToscaConstants.VF_MODULE_LABEL_PROPERTY_NAME); + return (List) parameterDefinitionExt.getAnnotations().get(ToscaConstants.SOURCE_ANNOTATION_ID).getProperties() + .get(ToscaConstants.VF_MODULE_LABEL_PROPERTY_NAME); } - private void translateOutputParameters(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - FileData heatFileData, String heatFileName, - TranslationContext context) { + private void translateOutputParameters(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + FileData heatFileData, String heatFileName, TranslationContext context) { if (heatOrchestrationTemplate.getOutputs() == null) { return; } - Map<String, ParameterDefinition> parameterDefinitionMap = - TranslatorHeatToToscaParameterConverter - .parameterOutputConverter(serviceTemplate, heatOrchestrationTemplate.getOutputs(), - heatOrchestrationTemplate, heatFileName, context); + Map<String, ParameterDefinition> parameterDefinitionMap = TranslatorHeatToToscaParameterConverter + .parameterOutputConverter(serviceTemplate, heatOrchestrationTemplate.getOutputs(), heatOrchestrationTemplate, heatFileName, context); if (serviceTemplate.getTopology_template().getOutputs() != null) { serviceTemplate.getTopology_template().getOutputs().putAll(parameterDefinitionMap); } else { serviceTemplate.getTopology_template().setOutputs(parameterDefinitionMap); } - if (heatFileData.getBase() != null && heatFileData.getBase().equals(true)) { - updateSharedResources(serviceTemplate, heatFileName, heatOrchestrationTemplate, - heatOrchestrationTemplate.getOutputs(), context); + updateSharedResources(serviceTemplate, heatFileName, heatOrchestrationTemplate, heatOrchestrationTemplate.getOutputs(), context); } } - private void updateSharedResources(ServiceTemplate serviceTemplate, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private void updateSharedResources(ServiceTemplate serviceTemplate, String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, Map<String, Output> outputs, TranslationContext context) { for (Map.Entry<String, Output> parameter : outputs.entrySet()) { Optional<AttachedResourceId> attachedSharedResourceId = HeatToToscaUtil - .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, - parameter.getValue().getValue()); + .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, parameter.getValue().getValue()); if (attachedSharedResourceId.isPresent() && attachedSharedResourceId.get().isGetResource() - && attachedSharedResourceId.get().getTranslatedId() != null) { - String sharedTranslatedResourceId = - attachedSharedResourceId.get().getTranslatedId().toString(); + && attachedSharedResourceId.get().getTranslatedId() != null) { + String sharedTranslatedResourceId = attachedSharedResourceId.get().getTranslatedId().toString(); updateSharedResource(serviceTemplate, context, parameter, sharedTranslatedResourceId, - heatOrchestrationTemplate.getResources() - .get(attachedSharedResourceId.get().getEntityId())); + heatOrchestrationTemplate.getResources().get(attachedSharedResourceId.get().getEntityId())); } else { Optional<String> contrailSharedResourceId = HeatToToscaUtil - .extractContrailGetResourceAttachedHeatResourceId(parameter.getValue().getValue()); + .extractContrailGetResourceAttachedHeatResourceId(parameter.getValue().getValue()); if (contrailSharedResourceId.isPresent() - && context.getTranslatedIds().get(heatFileName).get(contrailSharedResourceId.get()) - != null) { - String sharedTranslatedResourceId = context.getTranslatedIds().get(heatFileName).get - (contrailSharedResourceId.get()); - ConsolidationDataUtil.removeSharedResource(serviceTemplate, heatOrchestrationTemplate, - context, parameter.getKey(), contrailSharedResourceId.get(), sharedTranslatedResourceId); + && context.getTranslatedIds().get(heatFileName).get(contrailSharedResourceId.get()) != null) { + String sharedTranslatedResourceId = context.getTranslatedIds().get(heatFileName).get(contrailSharedResourceId.get()); + ConsolidationDataUtil + .removeSharedResource(serviceTemplate, heatOrchestrationTemplate, context, parameter.getKey(), contrailSharedResourceId.get(), + sharedTranslatedResourceId); updateSharedResource(serviceTemplate, context, parameter, sharedTranslatedResourceId, - heatOrchestrationTemplate.getResources().get(contrailSharedResourceId.get())); + heatOrchestrationTemplate.getResources().get(contrailSharedResourceId.get())); } } } - if (serviceTemplate.getTopology_template().getOutputs() != null - && serviceTemplate.getTopology_template().getOutputs().size() == 0) { + if (serviceTemplate.getTopology_template().getOutputs() != null && serviceTemplate.getTopology_template().getOutputs().size() == 0) { serviceTemplate.getTopology_template().setOutputs(null); } } - private void updateSharedResource(ServiceTemplate serviceTemplate, TranslationContext context, - Map.Entry<String, Output> paramName, + private void updateSharedResource(ServiceTemplate serviceTemplate, TranslationContext context, Map.Entry<String, Output> paramName, String sharedTranslatedResourceId, Resource resource) { context.addHeatSharedResourcesByParam(paramName.getKey(), sharedTranslatedResourceId, resource); serviceTemplate.getTopology_template().getOutputs().remove(paramName.getKey()); } - private void translateResources(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private void translateResources(String heatFileName, ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { return; } - for (String resourceId : heatOrchestrationTemplate.getResources().keySet()) { Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { - throw new CoreException( - new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); + throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); } ResourceTranslationFactory.getInstance(resource) - .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, resource, - resourceId, context); + .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, resource, resourceId, context); } } @@ -424,12 +357,9 @@ public class TranslationService { } for (FileData fileRelatedData : fileRelatedDataList) { if (fileRelatedData.getType().equals(FileData.Type.HEAT_ENV)) { - return new YamlUtil().yamlToObject(context.getFileContentAsStream(fileRelatedData.getFile()), - Environment.class); + return new YamlUtil().yamlToObject(context.getFileContentAsStream(fileRelatedData.getFile()), Environment.class); } } return new Environment(); } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java index 40e88ebdd5..dfe549679c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; +import java.util.List; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; -import java.util.List; - public interface UnifiedComposition { - void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List<UnifiedCompositionData> unifiedComposotionDataList, - TranslationContext context); - - + void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List<UnifiedCompositionData> unifiedComposotionDataList, TranslationContext context); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java index e057c7f17f..03bfd827cd 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java @@ -19,6 +19,9 @@ */ package org.openecomp.sdc.translator.services.heattotosca; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; @@ -29,97 +32,74 @@ import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileNestedConsolidationData; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - public class UnifiedCompositionManager { - private ConsolidationService consolidationService; - private TranslationService translationService = new TranslationService(); - private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - public UnifiedCompositionManager(ConsolidationService consolidationService) { - this.consolidationService = consolidationService; - } + private ConsolidationService consolidationService; + private TranslationService translationService = new TranslationService(); + private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - public UnifiedCompositionManager() { + public UnifiedCompositionManager(ConsolidationService consolidationService) { + this.consolidationService = consolidationService; + } - } + public UnifiedCompositionManager() { + } - /** - * Create unified composition. - * - * @param toscaServiceModel the tosca service model - * @param translationContext the translation context - * @return the tosca service model - */ - public ToscaServiceModel createUnifiedComposition(ToscaServiceModel toscaServiceModel, - TranslationContext translationContext) { - Map<String, ServiceTemplate> serviceTemplates = toscaServiceModel.getServiceTemplates(); - ServiceTemplate mainServiceTemplate = - serviceTemplates.get(toscaServiceModel.getEntryDefinitionServiceTemplate()); - createUnifiedComposition(toscaServiceModel, mainServiceTemplate, translationContext); - ToscaServiceModel unifiedToscaServiceModel = - HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); - return unifiedToscaServiceModel; - } + /** + * Create unified composition. + * + * @param toscaServiceModel the tosca service model + * @param translationContext the translation context + * @return the tosca service model + */ + public ToscaServiceModel createUnifiedComposition(ToscaServiceModel toscaServiceModel, TranslationContext translationContext) { + Map<String, ServiceTemplate> serviceTemplates = toscaServiceModel.getServiceTemplates(); + ServiceTemplate mainServiceTemplate = serviceTemplates.get(toscaServiceModel.getEntryDefinitionServiceTemplate()); + createUnifiedComposition(toscaServiceModel, mainServiceTemplate, translationContext); + ToscaServiceModel unifiedToscaServiceModel = HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); + return unifiedToscaServiceModel; + } - private void createUnifiedComposition(ToscaServiceModel toscaServiceModel, - ServiceTemplate serviceTemplate, - TranslationContext translationContext) { - handleNestedServiceTemplates(toscaServiceModel, serviceTemplate, translationContext); - consolidationService.serviceTemplateConsolidation(serviceTemplate, translationContext); - unifiedCompositionService - .updateUnifiedAbstractNodesConnectivity(serviceTemplate, translationContext); - translationContext.addUnifiedHandledServiceTeamplte(serviceTemplate); - } + private void createUnifiedComposition(ToscaServiceModel toscaServiceModel, ServiceTemplate serviceTemplate, + TranslationContext translationContext) { + handleNestedServiceTemplates(toscaServiceModel, serviceTemplate, translationContext); + consolidationService.serviceTemplateConsolidation(serviceTemplate, translationContext); + unifiedCompositionService.updateUnifiedAbstractNodesConnectivity(serviceTemplate, translationContext); + translationContext.addUnifiedHandledServiceTeamplte(serviceTemplate); + } - private void handleNestedServiceTemplates(ToscaServiceModel toscaServiceModel, - ServiceTemplate serviceTemplate, - TranslationContext translationContext) { - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - FileNestedConsolidationData fileNestedConsolidationData = - translationContext.getConsolidationData().getNestedConsolidationData() + private void handleNestedServiceTemplates(ToscaServiceModel toscaServiceModel, ServiceTemplate serviceTemplate, + TranslationContext translationContext) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + FileNestedConsolidationData fileNestedConsolidationData = translationContext.getConsolidationData().getNestedConsolidationData() .getFileNestedConsolidationData(serviceTemplateFileName); - - if (Objects.nonNull(fileNestedConsolidationData)) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - for (String substitutedNodeTemplateId : fileNestedConsolidationData - .getAllNestedNodeTemplateIds()) { - NodeTemplate nestedNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, substitutedNodeTemplateId); - if (Objects.isNull(nestedNodeTemplate) || translationContext - .isNestedNodeWasHandled(serviceTemplateFileName, substitutedNodeTemplateId)) { - continue; + if (Objects.nonNull(fileNestedConsolidationData)) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + for (String substitutedNodeTemplateId : fileNestedConsolidationData.getAllNestedNodeTemplateIds()) { + NodeTemplate nestedNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, substitutedNodeTemplateId); + if (Objects.isNull(nestedNodeTemplate) || translationContext + .isNestedNodeWasHandled(serviceTemplateFileName, substitutedNodeTemplateId)) { + continue; + } + Optional<String> substituteServiceTemplateName = toscaAnalyzerService + .getSubstituteServiceTemplateName(substitutedNodeTemplateId, nestedNodeTemplate); + if (substituteServiceTemplateName.isPresent()) { + ServiceTemplate substitutionServiceTemplate = toscaServiceModel.getServiceTemplates().get(substituteServiceTemplateName.get()); + createUnifiedCompositionForNestedServiceTemplate(toscaServiceModel, serviceTemplate, substitutionServiceTemplate, + substitutedNodeTemplateId, translationContext); + } + translationContext.addNestedNodeAsHandled(serviceTemplateFileName, substitutedNodeTemplateId); + } } - Optional<String> substituteServiceTemplateName = - toscaAnalyzerService.getSubstituteServiceTemplateName(substitutedNodeTemplateId, - nestedNodeTemplate); - if (substituteServiceTemplateName.isPresent()) { - ServiceTemplate substitutionServiceTemplate = - toscaServiceModel.getServiceTemplates().get(substituteServiceTemplateName.get()); - createUnifiedCompositionForNestedServiceTemplate(toscaServiceModel, serviceTemplate, - substitutionServiceTemplate, substitutedNodeTemplateId, translationContext); - } - translationContext.addNestedNodeAsHandled(serviceTemplateFileName, - substitutedNodeTemplateId); - } } - } - private void createUnifiedCompositionForNestedServiceTemplate( - ToscaServiceModel toscaServiceModel, - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - String substitutedNodeTemplateId, - TranslationContext translationContext) { - handleNestedServiceTemplates(toscaServiceModel, substitutionServiceTemplate, - translationContext); - consolidationService.substitutionServiceTemplateConsolidation(substitutedNodeTemplateId, - serviceTemplate, substitutionServiceTemplate, translationContext); - unifiedCompositionService - .updateUnifiedAbstractNodesConnectivity(substitutionServiceTemplate, translationContext); - translationContext.addUnifiedHandledServiceTeamplte(substitutionServiceTemplate); - } + private void createUnifiedCompositionForNestedServiceTemplate(ToscaServiceModel toscaServiceModel, ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, String substitutedNodeTemplateId, + TranslationContext translationContext) { + handleNestedServiceTemplates(toscaServiceModel, substitutionServiceTemplate, translationContext); + consolidationService + .substitutionServiceTemplateConsolidation(substitutedNodeTemplateId, serviceTemplate, substitutionServiceTemplate, translationContext); + unifiedCompositionService.updateUnifiedAbstractNodesConnectivity(substitutionServiceTemplate, translationContext); + translationContext.addUnifiedHandledServiceTeamplte(substitutionServiceTemplate); + } } - diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java index 77b5520a09..88f0b8f313 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import static org.openecomp.sdc.tosca.datatypes.ToscaFunctions.GET_INPUT; @@ -31,19 +30,18 @@ import static org.openecomp.sdc.translator.services.heattotosca.Constants.PORT_I import static org.openecomp.sdc.translator.services.heattotosca.Constants.SUB_INTERFACE_PROPERTY_VALUE_PREFIX; import static org.openecomp.sdc.translator.services.heattotosca.Constants.SUB_INTERFACE_ROLE; import static org.openecomp.sdc.translator.services.heattotosca.Constants.VFC_PARENT_PORT_ROLE; -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getPortTemplateConsolidationDataForPort; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getComputeTypeSuffix; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewComputeNodeTemplateId; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewPortNodeTemplateId; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewSubInterfaceNodeTemplateId; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getPortTemplateConsolidationDataForPort; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getSubInterfaceTemplateConsolidationDataList; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getSubInterfaceTypeSuffix; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimap; - import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; @@ -57,7 +55,6 @@ import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; - import org.apache.commons.collections.map.HashedMap; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; @@ -116,1177 +113,856 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida public class UnifiedCompositionService { - private static final Map<String, ImplementationConfiguration> unifiedCompositionImplMap; - - private static final EnumMap<UnifiedCompositionEntity, String> unifiedSubstitutionNodeTemplateIdGeneratorImplMap; - private static final String SUB_INTERFACE_INDICATOR_PROPERTY = "subinterface_indicator"; - private final ConsolidationService consolidationService = new ConsolidationService(); - - static { - Configuration config = ConfigurationManager.lookup(); - unifiedCompositionImplMap = - config.populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, - ConfigConstants.UNIFIED_COMPOSITION_IMPL_KEY, ImplementationConfiguration.class); - unifiedSubstitutionNodeTemplateIdGeneratorImplMap = new EnumMap<>(UnifiedCompositionEntity.class); - initNodeTemplateIdGeneratorImplMap(); - } - - private static void initNodeTemplateIdGeneratorImplMap() { - unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(COMPUTE, CommandImplNames - .COMPUTE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); - unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(PORT, CommandImplNames - .PORT_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); - unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(SUB_INTERFACE, CommandImplNames - .SUB_INTERFACE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); - } - - private static List<EntityConsolidationData> getPortConsolidationDataList( - List<String> portIds, - List<UnifiedCompositionData> unifiedCompositionDataList) { - return unifiedCompositionDataList.stream() + private static final Map<String, ImplementationConfiguration> unifiedCompositionImplMap; + private static final EnumMap<UnifiedCompositionEntity, String> unifiedSubstitutionNodeTemplateIdGeneratorImplMap; + private static final String SUB_INTERFACE_INDICATOR_PROPERTY = "subinterface_indicator"; + + static { + Configuration config = ConfigurationManager.lookup(); + unifiedCompositionImplMap = config + .populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants.UNIFIED_COMPOSITION_IMPL_KEY, + ImplementationConfiguration.class); + unifiedSubstitutionNodeTemplateIdGeneratorImplMap = new EnumMap<>(UnifiedCompositionEntity.class); + initNodeTemplateIdGeneratorImplMap(); + } + + private final ConsolidationService consolidationService = new ConsolidationService(); + + private static void initNodeTemplateIdGeneratorImplMap() { + unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(COMPUTE, CommandImplNames.COMPUTE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); + unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(PORT, CommandImplNames.PORT_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); + unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(SUB_INTERFACE, CommandImplNames.SUB_INTERFACE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); + } + + private static List<EntityConsolidationData> getPortConsolidationDataList(List<String> portIds, + List<UnifiedCompositionData> unifiedCompositionDataList) { + return unifiedCompositionDataList.stream() .flatMap(unifiedCompositionData -> unifiedCompositionData.getPortTemplateConsolidationDataList().stream()) .filter(portTemplateConsolidationData -> portIds.contains(portTemplateConsolidationData.getNodeTemplateId())) .collect(Collectors.toList()); - } - - /** - * Create unified composition. - * - * @param serviceTemplate the service template - * @param nestedServiceTemplate the nested service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param mode the mode - * @param context the context - */ - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - UnifiedCompositionMode mode, TranslationContext context) { - Optional<UnifiedComposition> unifiedCompositionInstance = getUnifiedCompositionInstance(mode); - if (!unifiedCompositionInstance.isPresent()) { - return; - } - unifiedCompositionInstance.get() - .createUnifiedComposition(serviceTemplate, nestedServiceTemplate, - unifiedCompositionDataList, context); - } - - /** - * Create unified substitution service template according to the input service template, based on - * the unified composition data. - * - * @param serviceTemplate the service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param context the translation context - * @return the substitution service template - */ - public Optional<ServiceTemplate> createUnifiedSubstitutionServiceTemplate( - ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context, - String substitutionNodeTypeId, - Integer index) { - if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { - return Optional.empty(); - } - String templateName = getTemplateName(substitutionNodeTypeId, index); - ServiceTemplate substitutionServiceTemplate = - HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); - - createIndexInputParameter(substitutionServiceTemplate); - - String computeNodeType = - handleCompute(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, - context); - handlePorts(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, - computeNodeType, context); - - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, - substitutionServiceTemplate, unifiedCompositionDataList, context, null); - handleSubInterfaces(unifiedCompositionTo); - createOutputParameters(unifiedCompositionTo, computeNodeType); - NodeType substitutionGlobalNodeType = - handleSubstitutionGlobalNodeType(serviceTemplate, substitutionServiceTemplate, - context, substitutionNodeTypeId); - - HeatToToscaUtil.handleSubstitutionMapping(context, - substitutionNodeTypeId, - substitutionServiceTemplate, substitutionGlobalNodeType); - - context.getTranslatedServiceTemplates().put(templateName, substitutionServiceTemplate); - return Optional.of(substitutionServiceTemplate); - } - - - /** - * Create abstract substitute node template that can be substituted by the input - * substitutionServiceTemplate. - * - * @param serviceTemplate the service template - * @param substitutionServiceTemplate the subtitution service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param context the translation context - * @return the abstract substitute node template id - */ - public String createAbstractSubstituteNodeTemplate( - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - String substituteNodeTypeId, - TranslationContext context, - Integer index) { - - NodeTemplate substitutionNodeTemplate = new NodeTemplate(); - List<String> directiveList = new ArrayList<>(); - directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); - substitutionNodeTemplate.setDirectives(directiveList); - substitutionNodeTemplate.setType(substituteNodeTypeId); - Map<String, ParameterDefinition> substitutionTemplateInputs = DataModelUtil - .getInputParameters(substitutionServiceTemplate); - Optional<Map<String, Object>> abstractSubstitutionProperties = Optional.empty(); - if (Objects.nonNull(substitutionTemplateInputs)) { - abstractSubstitutionProperties = createAbstractSubstitutionProperties(serviceTemplate, - substitutionTemplateInputs, unifiedCompositionDataList, context); - } - abstractSubstitutionProperties.ifPresent(substitutionNodeTemplate::setProperties); - - //Add substitution filtering property - String substitutionServiceTemplateName = ToscaUtil.getServiceTemplateFileName( - substitutionServiceTemplate); - int count = unifiedCompositionDataList.size(); - DataModelUtil.addSubstitutionFilteringProperty(substitutionServiceTemplateName, - substitutionNodeTemplate, count); - //Add index_value property - addIndexValueProperty(substitutionNodeTemplate); - String substituteNodeTemplateId = getSubstituteNodeTemplateId(substituteNodeTypeId, index); - //Add node template id and related abstract node template id in context - addUnifiedSubstitionData(context, serviceTemplate, unifiedCompositionDataList, - substituteNodeTemplateId); - DataModelUtil - .addNodeTemplate(serviceTemplate, substituteNodeTemplateId, substitutionNodeTemplate); - return substituteNodeTemplateId; - - } - - public void createVfcInstanceGroup(String abstractNodeTemplateId, - ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - if (!TranslationContext.isVfcInstanceGroupingEnabled()) { - return; - } - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, null, - unifiedCompositionDataList, context, null); - unifiedCompositionDataList.forEach(unifiedCompositionData -> - createSubInterfaceVfcInstanceGroup(abstractNodeTemplateId, unifiedCompositionTo, unifiedCompositionData)); - } - - private void createSubInterfaceVfcInstanceGroup(String abstractNodeTemplateId, - UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterface : subInterfaceTemplateConsolidationDataList) { - Optional<String> parentPortNetworkRole; - if (Objects.isNull(unifiedCompositionTo.getSubstitutionServiceTemplate())) { - parentPortNetworkRole = subInterface.getParentPortNetworkRole(unifiedCompositionTo.getServiceTemplate(), + } + + /** + * Create unified composition. + * + * @param serviceTemplate the service template + * @param nestedServiceTemplate the nested service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param mode the mode + * @param context the context + */ + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, UnifiedCompositionMode mode, + TranslationContext context) { + Optional<UnifiedComposition> unifiedCompositionInstance = getUnifiedCompositionInstance(mode); + if (!unifiedCompositionInstance.isPresent()) { + return; + } + unifiedCompositionInstance.get().createUnifiedComposition(serviceTemplate, nestedServiceTemplate, unifiedCompositionDataList, context); + } + + /** + * Create unified substitution service template according to the input service template, based on the unified composition data. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param context the translation context + * @return the substitution service template + */ + public Optional<ServiceTemplate> createUnifiedSubstitutionServiceTemplate(ServiceTemplate serviceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context, String substitutionNodeTypeId, + Integer index) { + if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { + return Optional.empty(); + } + String templateName = getTemplateName(substitutionNodeTypeId, index); + ServiceTemplate substitutionServiceTemplate = HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); + createIndexInputParameter(substitutionServiceTemplate); + String computeNodeType = handleCompute(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, context); + handlePorts(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, computeNodeType, context); + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, + context, null); + handleSubInterfaces(unifiedCompositionTo); + createOutputParameters(unifiedCompositionTo, computeNodeType); + NodeType substitutionGlobalNodeType = handleSubstitutionGlobalNodeType(serviceTemplate, substitutionServiceTemplate, context, + substitutionNodeTypeId); + HeatToToscaUtil.handleSubstitutionMapping(context, substitutionNodeTypeId, substitutionServiceTemplate, substitutionGlobalNodeType); + context.getTranslatedServiceTemplates().put(templateName, substitutionServiceTemplate); + return Optional.of(substitutionServiceTemplate); + } + + /** + * Create abstract substitute node template that can be substituted by the input substitutionServiceTemplate. + * + * @param serviceTemplate the service template + * @param substitutionServiceTemplate the subtitution service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param context the translation context + * @return the abstract substitute node template id + */ + public String createAbstractSubstituteNodeTemplate(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, String substituteNodeTypeId, + TranslationContext context, Integer index) { + NodeTemplate substitutionNodeTemplate = new NodeTemplate(); + List<String> directiveList = new ArrayList<>(); + directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); + substitutionNodeTemplate.setDirectives(directiveList); + substitutionNodeTemplate.setType(substituteNodeTypeId); + Map<String, ParameterDefinition> substitutionTemplateInputs = DataModelUtil.getInputParameters(substitutionServiceTemplate); + Optional<Map<String, Object>> abstractSubstitutionProperties = Optional.empty(); + if (Objects.nonNull(substitutionTemplateInputs)) { + abstractSubstitutionProperties = createAbstractSubstitutionProperties(serviceTemplate, substitutionTemplateInputs, + unifiedCompositionDataList, context); + } + abstractSubstitutionProperties.ifPresent(substitutionNodeTemplate::setProperties); + //Add substitution filtering property + String substitutionServiceTemplateName = ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate); + int count = unifiedCompositionDataList.size(); + DataModelUtil.addSubstitutionFilteringProperty(substitutionServiceTemplateName, substitutionNodeTemplate, count); + //Add index_value property + addIndexValueProperty(substitutionNodeTemplate); + String substituteNodeTemplateId = getSubstituteNodeTemplateId(substituteNodeTypeId, index); + //Add node template id and related abstract node template id in context + addUnifiedSubstitionData(context, serviceTemplate, unifiedCompositionDataList, substituteNodeTemplateId); + DataModelUtil.addNodeTemplate(serviceTemplate, substituteNodeTemplateId, substitutionNodeTemplate); + return substituteNodeTemplateId; + } + + public void createVfcInstanceGroup(String abstractNodeTemplateId, ServiceTemplate serviceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + if (!TranslationContext.isVfcInstanceGroupingEnabled()) { + return; + } + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, null, unifiedCompositionDataList, context, null); + unifiedCompositionDataList.forEach( + unifiedCompositionData -> createSubInterfaceVfcInstanceGroup(abstractNodeTemplateId, unifiedCompositionTo, unifiedCompositionData)); + } + + private void createSubInterfaceVfcInstanceGroup(String abstractNodeTemplateId, UnifiedCompositionTo unifiedCompositionTo, + UnifiedCompositionData unifiedCompositionData) { + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterface : subInterfaceTemplateConsolidationDataList) { + Optional<String> parentPortNetworkRole; + if (Objects.isNull(unifiedCompositionTo.getSubstitutionServiceTemplate())) { + parentPortNetworkRole = subInterface + .getParentPortNetworkRole(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getContext()); + } else { + parentPortNetworkRole = subInterface + .getParentPortNetworkRole(unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getContext()); + } + String subInterfaceNetworkRole = subInterface.getNetworkRole(); + if (Objects.nonNull(subInterfaceNetworkRole) && parentPortNetworkRole.isPresent()) { + createVfcInstanceGroupPerSubInterfaceNetworkRole(abstractNodeTemplateId, subInterfaceNetworkRole, parentPortNetworkRole.get(), + unifiedCompositionTo.getServiceTemplate()); + } + } + } + + private void createVfcInstanceGroupPerSubInterfaceNetworkRole(String abstractNodeTemplateId, String subInterfaceNetworkRole, + String parentPortNetworkRole, ServiceTemplate serviceTemplate) { + String vfcNetworkRoleGroupId = getVfcNetworkRoleGroupId(subInterfaceNetworkRole); + Map<String, GroupDefinition> groups = DataModelUtil.getGroups(serviceTemplate); + if (!groups.containsKey(vfcNetworkRoleGroupId)) { + createNewVfcInstanceGroup(serviceTemplate, parentPortNetworkRole, subInterfaceNetworkRole, vfcNetworkRoleGroupId); + } + DataModelUtil.addGroupMember(serviceTemplate, vfcNetworkRoleGroupId, abstractNodeTemplateId); + } + + private void createNewVfcInstanceGroup(ServiceTemplate serviceTemplate, String parentPortNetworkRole, String subInterfaceNetworkRole, + String vfcNetworkRoleGroupId) { + Map<String, Object> properties = new HashMap<>(); + properties.put(SUB_INTERFACE_ROLE, subInterfaceNetworkRole); + properties.put(VFC_PARENT_PORT_ROLE, parentPortNetworkRole); + updateVfcInstanceGroupExposedProperties(subInterfaceNetworkRole, serviceTemplate, properties); + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setType(GROUP_TYPE_PREFIX + VFC_INSTANCE_GROUP); + groupDefinition.setProperties(properties); + DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, vfcNetworkRoleGroupId, groupDefinition); + } + + private void updateVfcInstanceGroupExposedProperties(String subInterfaceNetworkRole, ServiceTemplate serviceTemplate, + Map<String, Object> properties) { + List<String> exposedVfcInstanceGroupingProperties = TranslationContext.getExposedVfcInstanceGroupingProperties(); + if (CollectionUtils.isEmpty(exposedVfcInstanceGroupingProperties)) { + return; + } + for (String propertyName : exposedVfcInstanceGroupingProperties) { + Map<String, Object> getInputMap = new HashMap<>(); + String vfcGroupPropertyInputName = subInterfaceNetworkRole + "_" + propertyName; + getInputMap.put(GET_INPUT.getFunctionName(), vfcGroupPropertyInputName); + properties.put(propertyName, getInputMap); + addInputParameter(vfcGroupPropertyInputName, PropertyType.STRING.getDisplayName(), null, serviceTemplate); + } + } + + private String getVfcNetworkRoleGroupId(String subInterfaceNetworkRole) { + StringBuilder sb = new StringBuilder(); + sb.append(subInterfaceNetworkRole).append("_").append(GROUP); + return sb.toString(); + } + + /** + * Update the connectivity from/to the "moved" nodes from the original service template to the new substitution service template. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param context the translation context + */ + public void updateCompositionConnectivity(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context) { + updOutputParamGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updNodesGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updNodesConnectedOutConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updNodesConnectedInConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updVolumeConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updGroupsConnectivity(serviceTemplate, unifiedCompositionDataList, context); + } + + /** + * Delete the "moved" nodes from the original service template to the new substitution service template. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param context the translation context + */ + public void cleanUnifiedCompositionEntities(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + //Clean compute node template data from top level service template + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + cleanServiceTemplate(serviceTemplate, computeTemplateConsolidationData, context); + //Clean port node template data from top level service template + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + cleanServiceTemplate(serviceTemplate, portTemplateConsolidationData, context); + } + //Clean sub-interface node template data from top level service template + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + cleanServiceTemplate(serviceTemplate, subInterfaceTemplateConsolidationData, context); + } + } + } + + /** + * Clean node types. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list + * @param context the context + */ + public void cleanNodeTypes(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + for (UnifiedCompositionData unifiedData : unifiedCompositionDataList) { + removeCleanedNodeType(unifiedData.getComputeTemplateConsolidationData().getNodeTemplateId(), serviceTemplate, context); + } + if (MapUtils.isEmpty(serviceTemplate.getNode_types())) { + serviceTemplate.setNode_types(null); + } + } + + public void updateSubstitutionNodeTypePrefix(ServiceTemplate substitutionServiceTemplate) { + Map<String, NodeTemplate> nodeTemplates = substitutionServiceTemplate.getTopology_template().getNode_templates(); + for (Map.Entry<String, NodeTemplate> nodeTemplateEntry : nodeTemplates.entrySet()) { + String nodeTypeId = nodeTemplateEntry.getValue().getType(); + NodeType origNodeType = substitutionServiceTemplate.getNode_types().get(nodeTypeId); + if (Objects.nonNull(origNodeType) && nodeTypeId.startsWith(ToscaNodeType.VFC_TYPE_PREFIX) && origNodeType.getDerived_from() + .equals(ToscaNodeType.NOVA_SERVER)) { + substitutionServiceTemplate.getNode_types().remove(nodeTypeId); + String newNodeTypeId = nodeTypeId.replace(ToscaNodeType.VFC_TYPE_PREFIX, ToscaNodeType.COMPUTE_TYPE_PREFIX); + nodeTemplateEntry.getValue().setType(newNodeTypeId); + DataModelUtil.addNodeTemplate(substitutionServiceTemplate, nodeTemplateEntry.getKey(), nodeTemplateEntry.getValue()); + substitutionServiceTemplate.getNode_types().put(newNodeTypeId, origNodeType); + } + } + } + + /** + * Update unified abstract nodes connectivity. + * + * @param serviceTemplate the service template + * @param context the context + */ + public void updateUnifiedAbstractNodesConnectivity(ServiceTemplate serviceTemplate, TranslationContext context) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + UnifiedSubstitutionData unifiedSubstitutionData = context.getUnifiedSubstitutionData().get(serviceTemplateFileName); + if (Objects.nonNull(unifiedSubstitutionData)) { + //Handle get attribute in connectivity for abstarct node to abstract node templates + Set<String> abstractNodeIds = new HashSet<>(unifiedSubstitutionData.getAllRelatedAbstractNodeIds()); + handleGetAttrInConnectivity(serviceTemplate, abstractNodeIds, context); + //Handle get attribute in connectivity for abstract node templates to nested node template + Set<String> nestedNodeIds = new HashSet<>(unifiedSubstitutionData.getAllUnifiedNestedNodeTemplateIds()); + handleGetAttrInConnectivity(serviceTemplate, nestedNodeIds, context); + } + } + + /** + * Handle unified nested definition. + * + * @param unifiedCompositionTo the unified composition data transfer object + * @param unifiedCompositionData the unified composition data + */ + public void handleUnifiedNestedDefinition(UnifiedCompositionTo unifiedCompositionTo, UnifiedCompositionData unifiedCompositionData) { + handleUnifiedNestedNodeType(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getContext()); - } else { - parentPortNetworkRole = subInterface.getParentPortNetworkRole(unifiedCompositionTo - .getSubstitutionServiceTemplate(), unifiedCompositionTo.getContext()); - } - String subInterfaceNetworkRole = subInterface.getNetworkRole(); - if (Objects.nonNull(subInterfaceNetworkRole) && parentPortNetworkRole.isPresent()) { - createVfcInstanceGroupPerSubInterfaceNetworkRole(abstractNodeTemplateId, subInterfaceNetworkRole, - parentPortNetworkRole.get(), unifiedCompositionTo.getServiceTemplate()); - } - } - } - - private void createVfcInstanceGroupPerSubInterfaceNetworkRole(String abstractNodeTemplateId, - String subInterfaceNetworkRole, - String parentPortNetworkRole, - ServiceTemplate serviceTemplate) { - String vfcNetworkRoleGroupId = getVfcNetworkRoleGroupId(subInterfaceNetworkRole); - Map<String, GroupDefinition> groups = DataModelUtil.getGroups(serviceTemplate); - if (!groups.containsKey(vfcNetworkRoleGroupId)) { - createNewVfcInstanceGroup(serviceTemplate, parentPortNetworkRole, subInterfaceNetworkRole, vfcNetworkRoleGroupId); - } - DataModelUtil.addGroupMember(serviceTemplate, vfcNetworkRoleGroupId, abstractNodeTemplateId); - } - - private void createNewVfcInstanceGroup(ServiceTemplate serviceTemplate, - String parentPortNetworkRole, - String subInterfaceNetworkRole, - String vfcNetworkRoleGroupId) { - Map<String, Object> properties = new HashMap<>(); - properties.put(SUB_INTERFACE_ROLE, subInterfaceNetworkRole); - properties.put(VFC_PARENT_PORT_ROLE, parentPortNetworkRole); - - updateVfcInstanceGroupExposedProperties(subInterfaceNetworkRole, - serviceTemplate, properties); - - GroupDefinition groupDefinition = new GroupDefinition(); - groupDefinition.setType(GROUP_TYPE_PREFIX + VFC_INSTANCE_GROUP); - groupDefinition.setProperties(properties); - - DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, - vfcNetworkRoleGroupId, groupDefinition); - } - - private void updateVfcInstanceGroupExposedProperties(String subInterfaceNetworkRole, - ServiceTemplate serviceTemplate, - Map<String, Object> properties) { - List<String> exposedVfcInstanceGroupingProperties = - TranslationContext.getExposedVfcInstanceGroupingProperties(); - - if (CollectionUtils.isEmpty(exposedVfcInstanceGroupingProperties)) { - return; - } - - for (String propertyName : exposedVfcInstanceGroupingProperties) { - Map<String, Object> getInputMap = new HashMap<>(); - String vfcGroupPropertyInputName = subInterfaceNetworkRole + "_" + propertyName; - getInputMap.put(GET_INPUT.getFunctionName(), vfcGroupPropertyInputName); - properties.put(propertyName, getInputMap); - - addInputParameter(vfcGroupPropertyInputName, PropertyType.STRING.getDisplayName(), null, - serviceTemplate); - } - } - - private String getVfcNetworkRoleGroupId(String subInterfaceNetworkRole) { - StringBuilder sb = new StringBuilder(); - sb.append(subInterfaceNetworkRole).append("_").append(GROUP); - return sb.toString(); - } - - /** - * Update the connectivity from/to the "moved" nodes from the original service template to the new - * substitution service template. - * - * @param serviceTemplate the service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param context the translation context - */ - public void updateCompositionConnectivity(ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - updOutputParamGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updNodesGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updNodesConnectedOutConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updNodesConnectedInConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updVolumeConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updGroupsConnectivity(serviceTemplate, unifiedCompositionDataList, context); - } - - /** - * Delete the "moved" nodes from the original service template to the new substitution service - * template. - * - * @param serviceTemplate the service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param context the translation context - */ - public void cleanUnifiedCompositionEntities( - ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - //Clean compute node template data from top level service template - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - cleanServiceTemplate(serviceTemplate, computeTemplateConsolidationData, context); - - //Clean port node template data from top level service template - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - cleanServiceTemplate(serviceTemplate, portTemplateConsolidationData, context); - } - - //Clean sub-interface node template data from top level service template - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - cleanServiceTemplate(serviceTemplate, subInterfaceTemplateConsolidationData, context); - } - } - } - - /** - * Clean node types. - * - * @param serviceTemplate the service template - * @param unifiedCompositionDataList the unified composition data list - * @param context the context - */ - public void cleanNodeTypes(ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedData : unifiedCompositionDataList) { - removeCleanedNodeType( - unifiedData.getComputeTemplateConsolidationData().getNodeTemplateId(), serviceTemplate, - context); - } - if (MapUtils.isEmpty(serviceTemplate.getNode_types())) { - serviceTemplate.setNode_types(null); - } - } - - public void updateSubstitutionNodeTypePrefix(ServiceTemplate substitutionServiceTemplate) { - Map<String, NodeTemplate> nodeTemplates = - substitutionServiceTemplate.getTopology_template().getNode_templates(); - - for (Map.Entry<String, NodeTemplate> nodeTemplateEntry : nodeTemplates.entrySet()) { - String nodeTypeId = nodeTemplateEntry.getValue().getType(); - NodeType origNodeType = substitutionServiceTemplate.getNode_types().get(nodeTypeId); - if (Objects.nonNull(origNodeType) - && nodeTypeId.startsWith(ToscaNodeType.VFC_TYPE_PREFIX) - && origNodeType.getDerived_from().equals(ToscaNodeType.NOVA_SERVER)) { - substitutionServiceTemplate.getNode_types().remove(nodeTypeId); - - String newNodeTypeId = - nodeTypeId.replace(ToscaNodeType.VFC_TYPE_PREFIX, ToscaNodeType.COMPUTE_TYPE_PREFIX); - nodeTemplateEntry.getValue().setType(newNodeTypeId); - DataModelUtil - .addNodeTemplate(substitutionServiceTemplate, nodeTemplateEntry.getKey(), - nodeTemplateEntry.getValue()); - substitutionServiceTemplate.getNode_types().put(newNodeTypeId, origNodeType); - } - } - } - - /** - * Update unified abstract nodes connectivity. - * - * @param serviceTemplate the service template - * @param context the context - */ - public void updateUnifiedAbstractNodesConnectivity(ServiceTemplate serviceTemplate, - TranslationContext context) { + updateUnifiedNestedTemplates(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getSubstitutionServiceTemplate(), + unifiedCompositionData, unifiedCompositionTo.getContext()); + } + private void handleGetAttrInConnectivity(ServiceTemplate serviceTemplate, Set<String> unifiedNodeIds, TranslationContext context) { + Map<String, NodeTemplate> nodeTemplates = serviceTemplate.getTopology_template().getNode_templates(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + for (String unifiedNodeId : unifiedNodeIds) { + NodeTemplate nodeTemplate = nodeTemplates.get(unifiedNodeId); + handleGetAttrInAbstractNodeTemplate(serviceTemplate, context, serviceTemplateFileName, nodeTemplate); + } + } - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - UnifiedSubstitutionData unifiedSubstitutionData = context.getUnifiedSubstitutionData() - .get(serviceTemplateFileName); - - if (Objects.nonNull(unifiedSubstitutionData)) { - //Handle get attribute in connectivity for abstarct node to abstract node templates - Set<String> abstractNodeIds = - new HashSet<>(unifiedSubstitutionData.getAllRelatedAbstractNodeIds()); - handleGetAttrInConnectivity(serviceTemplate, abstractNodeIds, context); - //Handle get attribute in connectivity for abstract node templates to nested node template - Set<String> nestedNodeIds = - new HashSet<>(unifiedSubstitutionData.getAllUnifiedNestedNodeTemplateIds()); - handleGetAttrInConnectivity(serviceTemplate, nestedNodeIds, context); - } - } - - /** - * Handle unified nested definition. - * - * @param unifiedCompositionTo the unified composition data transfer object - * @param unifiedCompositionData the unified composition data - */ - public void handleUnifiedNestedDefinition(UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - handleUnifiedNestedNodeType(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo - .getSubstitutionServiceTemplate(), unifiedCompositionTo.getContext()); - updateUnifiedNestedTemplates(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo - .getSubstitutionServiceTemplate(), unifiedCompositionData, unifiedCompositionTo.getContext()); - } - - private void handleGetAttrInConnectivity(ServiceTemplate serviceTemplate, - Set<String> unifiedNodeIds, - TranslationContext context) { - Map<String, NodeTemplate> nodeTemplates = - serviceTemplate.getTopology_template().getNode_templates(); - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - for (String unifiedNodeId : unifiedNodeIds) { - NodeTemplate nodeTemplate = nodeTemplates.get(unifiedNodeId); - handleGetAttrInAbstractNodeTemplate(serviceTemplate, context, serviceTemplateFileName, - nodeTemplate); - } - } - - private void handleUnifiedNestedNodeType(ServiceTemplate mainServiceTemplate, - ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - - - SubstitutionMapping substitutionMappings = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); - String nodeTypeId = substitutionMappings.getNode_type(); - - Optional<String> newNestedNodeTypeId = getNewNestedNodeTypeId(nestedServiceTemplate, context); - - ServiceTemplate globalSubstitutionServiceTemplate = - context.getGlobalSubstitutionServiceTemplate(); - - if (isNestedServiceTemplateWasHandled(globalSubstitutionServiceTemplate, nestedServiceTemplate, - context, - newNestedNodeTypeId)) { - context - .updateHandledComputeType(ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), - newNestedNodeTypeId.get(), - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); - return; - } - - - newNestedNodeTypeId.ifPresent( - newNestedNodeTypeIdVal -> handleNestedNodeType(nodeTypeId, newNestedNodeTypeIdVal, - nestedServiceTemplate, mainServiceTemplate, globalSubstitutionServiceTemplate, - context)); - - } - - private boolean isNestedServiceTemplateWasHandled(ServiceTemplate mainServiceTemplate, - ServiceTemplate nestedServiceTemplate, - TranslationContext context, - Optional<String> newNestedNodeTypeId) { - return newNestedNodeTypeId.isPresent() - && context.isNestedServiceTemplateWasHandled( - ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + private void handleUnifiedNestedNodeType(ServiceTemplate mainServiceTemplate, ServiceTemplate nestedServiceTemplate, TranslationContext context) { + SubstitutionMapping substitutionMappings = nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); + String nodeTypeId = substitutionMappings.getNode_type(); + Optional<String> newNestedNodeTypeId = getNewNestedNodeTypeId(nestedServiceTemplate, context); + ServiceTemplate globalSubstitutionServiceTemplate = context.getGlobalSubstitutionServiceTemplate(); + if (isNestedServiceTemplateWasHandled(globalSubstitutionServiceTemplate, nestedServiceTemplate, context, newNestedNodeTypeId)) { + context.updateHandledComputeType(ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), newNestedNodeTypeId.get(), + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + return; + } + newNestedNodeTypeId.ifPresent( + newNestedNodeTypeIdVal -> handleNestedNodeType(nodeTypeId, newNestedNodeTypeIdVal, nestedServiceTemplate, mainServiceTemplate, + globalSubstitutionServiceTemplate, context)); + } + + private boolean isNestedServiceTemplateWasHandled(ServiceTemplate mainServiceTemplate, ServiceTemplate nestedServiceTemplate, + TranslationContext context, Optional<String> newNestedNodeTypeId) { + return newNestedNodeTypeId.isPresent() && context.isNestedServiceTemplateWasHandled(ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); - } + } + + private void handleNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, ServiceTemplate nestedServiceTemplate, + ServiceTemplate mainServiceTemplate, ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + updateNestedServiceTemplate(nestedServiceTemplate, context); + updateNestedNodeType(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, mainServiceTemplate, globalSubstitutionServiceTemplate, context); + } + + private void updateNestedServiceTemplate(ServiceTemplate nestedServiceTemplate, TranslationContext context) { + enrichPortProperties(nestedServiceTemplate, context); + } + + private void enrichPortProperties(ServiceTemplate nestedServiceTemplate, TranslationContext context) { + String nestedServiceTemplateFileName = ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate); + FilePortConsolidationData filePortConsolidationData = context.getConsolidationData().getPortConsolidationData() + .getFilePortConsolidationData(nestedServiceTemplateFileName); + if (Objects.nonNull(filePortConsolidationData)) { + Set<String> portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); + if (Objects.nonNull(portNodeTemplateIds)) { + for (String portNodeTemplateId : portNodeTemplateIds) { + NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(nestedServiceTemplate, portNodeTemplateId); + List<EntityConsolidationData> portEntityConsolidationDataList = new ArrayList<>(); + portEntityConsolidationDataList.add(filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId)); + handleNodeTypeProperties(nestedServiceTemplate, portEntityConsolidationDataList, portNodeTemplate, UnifiedCompositionEntity.PORT, + null, context); + //Add subinterface_indicator property to PORT + addPortSubInterfaceIndicatorProperty(portNodeTemplate.getProperties(), + filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId)); + } + } + } + } + + private void updateNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, ServiceTemplate nestedServiceTemplate, + ServiceTemplate mainServiceTemplate, ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + String indexedNewNestedNodeTypeId = updateNodeTypeId(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, mainServiceTemplate, + globalSubstitutionServiceTemplate, context); + updateNodeTypeProperties(nestedServiceTemplate, globalSubstitutionServiceTemplate, indexedNewNestedNodeTypeId); + } - private void handleNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, - ServiceTemplate nestedServiceTemplate, - ServiceTemplate mainServiceTemplate, - ServiceTemplate globalSubstitutionServiceTemplate, + private void updateNodeTypeProperties(ServiceTemplate nestedServiceTemplate, ServiceTemplate globalSubstitutionServiceTemplate, + String nodeTypeId) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + Map<String, PropertyDefinition> nodeTypePropertiesDefinition = toscaAnalyzerService + .manageSubstitutionNodeTypeProperties(nestedServiceTemplate); + NodeType nestedNodeType = DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, nodeTypeId); + nestedNodeType.setProperties(nodeTypePropertiesDefinition); + } + + private String updateNodeTypeId(String nodeTypeId, String newNestedNodeTypeId, ServiceTemplate nestedServiceTemplate, + ServiceTemplate mainServiceTemplate, ServiceTemplate globalSubstitutionServiceTemplate, TranslationContext context) { - updateNestedServiceTemplate(nestedServiceTemplate, context); - updateNestedNodeType(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, - mainServiceTemplate, + String indexedNewNestedNodeTypeId = handleNestedNodeTypeInGlobalSubstitutionTemplate(nodeTypeId, newNestedNodeTypeId, globalSubstitutionServiceTemplate, context); + handleSubstitutionMappingInNestedServiceTemplate(indexedNewNestedNodeTypeId, nestedServiceTemplate, context); + context.updateHandledComputeType(ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), newNestedNodeTypeId); + return indexedNewNestedNodeTypeId; + } + private String handleNestedNodeTypeInGlobalSubstitutionTemplate(String nodeTypeId, String newNestedNodeTypeId, + ServiceTemplate globalSubstitutionServiceTemplate, TranslationContext context) { + String indexedNodeType = getIndexedGlobalNodeTypeId(newNestedNodeTypeId, context); + context.updateUsedTimesForNestedComputeNodeType(ToscaUtil.getServiceTemplateFileName(globalSubstitutionServiceTemplate), newNestedNodeTypeId); + handleNestedNodeTypesInGlobalSubstituteServiceTemplate(nodeTypeId, indexedNodeType, globalSubstitutionServiceTemplate, context); + return indexedNodeType; + } - } + private String getIndexedGlobalNodeTypeId(String newNestedNodeTypeId, TranslationContext context) { + int globalNodeTypeIndex = context + .getGlobalNodeTypeIndex(ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME), newNestedNodeTypeId); + return globalNodeTypeIndex > 0 ? newNestedNodeTypeId + "_" + globalNodeTypeIndex : newNestedNodeTypeId; + } - private void updateNestedServiceTemplate(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - enrichPortProperties(nestedServiceTemplate, context); - } + private void updateUnifiedNestedTemplates(ServiceTemplate mainServiceTemplate, ServiceTemplate nestedServiceTemplate, + UnifiedCompositionData unifiedCompositionData, TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.isNull(nestedTemplateConsolidationData)) { + return; + } + handleNestedNodeTemplateInMainServiceTemplate(nestedTemplateConsolidationData.getNodeTemplateId(), mainServiceTemplate, nestedServiceTemplate, + context); + } - private void enrichPortProperties(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - String nestedServiceTemplateFileName = - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate); - FilePortConsolidationData filePortConsolidationData = - context.getConsolidationData().getPortConsolidationData().getFilePortConsolidationData - (nestedServiceTemplateFileName); - - if (Objects.nonNull(filePortConsolidationData)) { - Set<String> portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); - if (Objects.nonNull(portNodeTemplateIds)) { - for (String portNodeTemplateId : portNodeTemplateIds) { - NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(nestedServiceTemplate, - portNodeTemplateId); - List<EntityConsolidationData> portEntityConsolidationDataList = new ArrayList<>(); - portEntityConsolidationDataList.add(filePortConsolidationData - .getPortTemplateConsolidationData(portNodeTemplateId)); - - handleNodeTypeProperties(nestedServiceTemplate, - portEntityConsolidationDataList, portNodeTemplate, UnifiedCompositionEntity.PORT, - null, context); - //Add subinterface_indicator property to PORT - addPortSubInterfaceIndicatorProperty(portNodeTemplate.getProperties(), - filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId)); - } - } - } - } - - private void updateNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, - ServiceTemplate nestedServiceTemplate, - ServiceTemplate mainServiceTemplate, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { - String indexedNewNestedNodeTypeId = - updateNodeTypeId(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, - mainServiceTemplate, - globalSubstitutionServiceTemplate, context); - - updateNodeTypeProperties(nestedServiceTemplate, globalSubstitutionServiceTemplate, - indexedNewNestedNodeTypeId); - } - - private void updateNodeTypeProperties(ServiceTemplate nestedServiceTemplate, - ServiceTemplate globalSubstitutionServiceTemplate, - String nodeTypeId) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - Map<String, PropertyDefinition> nodeTypePropertiesDefinition = - toscaAnalyzerService.manageSubstitutionNodeTypeProperties(nestedServiceTemplate); - NodeType nestedNodeType = - DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, nodeTypeId); - nestedNodeType.setProperties(nodeTypePropertiesDefinition); - } - - private String updateNodeTypeId(String nodeTypeId, String newNestedNodeTypeId, - ServiceTemplate nestedServiceTemplate, - ServiceTemplate mainServiceTemplate, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { - String indexedNewNestedNodeTypeId = - handleNestedNodeTypeInGlobalSubstitutionTemplate(nodeTypeId, newNestedNodeTypeId, - globalSubstitutionServiceTemplate, context); - - handleSubstitutionMappingInNestedServiceTemplate(indexedNewNestedNodeTypeId, - nestedServiceTemplate, context); - - context - .updateHandledComputeType( - ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), - newNestedNodeTypeId); - return indexedNewNestedNodeTypeId; - } - - private String handleNestedNodeTypeInGlobalSubstitutionTemplate(String nodeTypeId, - String newNestedNodeTypeId, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { - String indexedNodeType = - getIndexedGlobalNodeTypeId(newNestedNodeTypeId, context); - context.updateUsedTimesForNestedComputeNodeType( - ToscaUtil.getServiceTemplateFileName(globalSubstitutionServiceTemplate), - newNestedNodeTypeId); - handleNestedNodeTypesInGlobalSubstituteServiceTemplate(nodeTypeId, indexedNodeType, - globalSubstitutionServiceTemplate, context); - return indexedNodeType; - } + /** + * Update connectivity for unified nested patterns. + * + * @param unifiedCompositionTo the unified composition data transfer object + * @param unifiedCompositionData the unified composition data + */ + public void updateUnifiedNestedConnectivity(UnifiedCompositionTo unifiedCompositionTo, UnifiedCompositionData unifiedCompositionData) { + updNestedCompositionNodesConnectedInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, + unifiedCompositionTo.getContext()); + updNestedCompositionNodesConnectedOutConnectivity(unifiedCompositionTo.getServiceTemplate(), + unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionData, unifiedCompositionTo.getContext()); + updNestedCompositionNodesGetAttrInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, + unifiedCompositionTo.getContext()); + updNestedCompositionOutputParamGetAttrInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, + unifiedCompositionTo.getContext()); + } - private String getIndexedGlobalNodeTypeId(String newNestedNodeTypeId, - TranslationContext context) { - int globalNodeTypeIndex = - context.getGlobalNodeTypeIndex( - ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME), - newNestedNodeTypeId); - return globalNodeTypeIndex > 0 ? newNestedNodeTypeId + "_" - + globalNodeTypeIndex : newNestedNodeTypeId; - } - - private void updateUnifiedNestedTemplates(ServiceTemplate mainServiceTemplate, - ServiceTemplate nestedServiceTemplate, - UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { + /** + * Clean unified nested entities. Update the heat stack group with the new node template ids. + * + * @param unifiedCompositionTo the unified composition data transfer object + * @param unifiedCompositionData the unified composition data + */ + public void cleanUnifiedNestedEntities(UnifiedCompositionTo unifiedCompositionTo, UnifiedCompositionData unifiedCompositionData) { + EntityConsolidationData entityConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + updateHeatStackGroupNestedComposition(unifiedCompositionTo.getServiceTemplate(), entityConsolidationData, unifiedCompositionTo.getContext()); + } - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - if (Objects.isNull(nestedTemplateConsolidationData)) { - return; - } - handleNestedNodeTemplateInMainServiceTemplate( - nestedTemplateConsolidationData.getNodeTemplateId(), mainServiceTemplate, - nestedServiceTemplate, context); - } - - /** - * Update connectivity for unified nested patterns. - * - * @param unifiedCompositionTo the unified composition data transfer object - * @param unifiedCompositionData the unified composition data - */ - public void updateUnifiedNestedConnectivity(UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - - updNestedCompositionNodesConnectedInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, - unifiedCompositionTo.getContext()); - updNestedCompositionNodesConnectedOutConnectivity(unifiedCompositionTo.getServiceTemplate(), - unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionData, unifiedCompositionTo - .getContext()); - updNestedCompositionNodesGetAttrInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, - unifiedCompositionTo.getContext()); - updNestedCompositionOutputParamGetAttrInConnectivity(unifiedCompositionTo.getServiceTemplate(), - unifiedCompositionData, unifiedCompositionTo.getContext()); - } - - - /** - * Clean unified nested entities. Update the heat stack group with the new node template ids. - * - * @param unifiedCompositionTo the unified composition data transfer object - * @param unifiedCompositionData the unified composition data - */ - public void cleanUnifiedNestedEntities(UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - EntityConsolidationData entityConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - updateHeatStackGroupNestedComposition(unifiedCompositionTo.getServiceTemplate(), entityConsolidationData, - unifiedCompositionTo.getContext()); - - } - - public void createNestedVfcInstanceGroup(String nestedNodeTemplateId, - UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - if (!TranslationContext.isVfcInstanceGroupingEnabled()) { - return; - } - createSubInterfaceVfcInstanceGroup(nestedNodeTemplateId, unifiedCompositionTo, unifiedCompositionData); - } - - public void handleComplexVfcType(ServiceTemplate serviceTemplate, TranslationContext context) { - SubstitutionMapping substitutionMapping = - serviceTemplate.getTopology_template().getSubstitution_mappings(); - - if (Objects.isNull(substitutionMapping)) { - return; - } - - ServiceTemplate globalSubstitutionServiceTemplate = - context.getGlobalSubstitutionServiceTemplate(); - - String substitutionNT = substitutionMapping.getNode_type(); - if (globalSubstitutionServiceTemplate.getNode_types().containsKey(substitutionNT)) { - //This needs to be done when catalog is ready for complex VFC - } - } - - - protected void updNodesConnectedOutConnectivity(ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> - unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - //Add requirements in the abstract node template for nodes connected out for computes - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - Multimap<String, RequirementAssignmentData> computeNodesConnectedOut = - computeTemplateConsolidationData.getNodesConnectedOut(); - if (computeNodesConnectedOut != null) { - updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, - newComputeNodeTemplateId, computeNodesConnectedOut, context); - } - String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData - .getNodeTemplateId()); - //Add requirements in the abstract node template for nodes connected out for ports - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData - .getNodeTemplateId(), computeType, computeTemplateConsolidationData); - Multimap<String, RequirementAssignmentData> portNodesConnectedOut = - portTemplateConsolidationData.getNodesConnectedOut(); - if (portNodesConnectedOut != null) { - updateRequirementInAbstractNodeTemplate(serviceTemplate, portTemplateConsolidationData, - newPortNodeTemplateId, portNodesConnectedOut, context); - } - } - //For sub-interface - //Add requirements in the abstract node template for nodes connected out for ports - updateSubInterfaceNodesConnectedOut(serviceTemplate, unifiedCompositionData, - computeTemplateConsolidationData, computeType, context); - } - } - - private void updateSubInterfaceNodesConnectedOut(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - String computeType, - TranslationContext context) { - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, - computeTemplateConsolidationData, subInterfaceTemplateConsolidationData, context); - Multimap<String, RequirementAssignmentData> subInterfaceNodesConnectedOut = - subInterfaceTemplateConsolidationData.getNodesConnectedOut(); - if (subInterfaceNodesConnectedOut != null) { - updateRequirementInAbstractNodeTemplate(serviceTemplate, subInterfaceTemplateConsolidationData, - newSubInterfaceNodeTemplateId, subInterfaceNodesConnectedOut, context); - } - } - } - - private void updNestedCompositionNodesConnectedOutConnectivity(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - Multimap<String, RequirementAssignmentData> nodesConnectedOut = - Objects.isNull(nestedTemplateConsolidationData) ? ArrayListMultimap.create() - : nestedTemplateConsolidationData.getNodesConnectedOut(); + public void createNestedVfcInstanceGroup(String nestedNodeTemplateId, UnifiedCompositionTo unifiedCompositionTo, + UnifiedCompositionData unifiedCompositionData) { + if (!TranslationContext.isVfcInstanceGroupingEnabled()) { + return; + } + createSubInterfaceVfcInstanceGroup(nestedNodeTemplateId, unifiedCompositionTo, unifiedCompositionData); + } + + public void handleComplexVfcType(ServiceTemplate serviceTemplate, TranslationContext context) { + SubstitutionMapping substitutionMapping = serviceTemplate.getTopology_template().getSubstitution_mappings(); + if (Objects.isNull(substitutionMapping)) { + return; + } + ServiceTemplate globalSubstitutionServiceTemplate = context.getGlobalSubstitutionServiceTemplate(); + String substitutionNT = substitutionMapping.getNode_type(); + if (globalSubstitutionServiceTemplate.getNode_types().containsKey(substitutionNT)) { + //This needs to be done when catalog is ready for complex VFC + } + } - FileComputeConsolidationData nestedFileComputeConsolidationData = - context.getConsolidationData().getComputeConsolidationData().getFileComputeConsolidationData - (ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + protected void updNodesConnectedOutConnectivity(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + //Add requirements in the abstract node template for nodes connected out for computes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + Multimap<String, RequirementAssignmentData> computeNodesConnectedOut = computeTemplateConsolidationData.getNodesConnectedOut(); + if (computeNodesConnectedOut != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, newComputeNodeTemplateId, + computeNodesConnectedOut, context); + } + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + //Add requirements in the abstract node template for nodes connected out for ports + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + Multimap<String, RequirementAssignmentData> portNodesConnectedOut = portTemplateConsolidationData.getNodesConnectedOut(); + if (portNodesConnectedOut != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, portTemplateConsolidationData, newPortNodeTemplateId, + portNodesConnectedOut, context); + } + } + //For sub-interface - if (Objects.isNull(nestedFileComputeConsolidationData)) { - return; + //Add requirements in the abstract node template for nodes connected out for ports + updateSubInterfaceNodesConnectedOut(serviceTemplate, unifiedCompositionData, computeTemplateConsolidationData, computeType, context); + } } - TypeComputeConsolidationData computeType = - nestedFileComputeConsolidationData.getAllTypeComputeConsolidationData().iterator().next(); - if (Objects.isNull(computeType)) { - return; + private void updateSubInterfaceNodesConnectedOut(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + ComputeTemplateConsolidationData computeTemplateConsolidationData, String computeType, + TranslationContext context) { + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, computeTemplateConsolidationData, + subInterfaceTemplateConsolidationData, context); + Multimap<String, RequirementAssignmentData> subInterfaceNodesConnectedOut = subInterfaceTemplateConsolidationData.getNodesConnectedOut(); + if (subInterfaceNodesConnectedOut != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplateId, + subInterfaceNodesConnectedOut, context); + } + } } - String singleComputeId = computeType.getAllComputeNodeTemplateIds().iterator().next(); - if (Objects.nonNull(singleComputeId) && (Objects.nonNull(nestedTemplateConsolidationData))) { - updateRequirementInNestedNodeTemplate(serviceTemplate, nestedTemplateConsolidationData, - singleComputeId, nodesConnectedOut); + private void updNestedCompositionNodesConnectedOutConnectivity(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + UnifiedCompositionData unifiedCompositionData, TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + Multimap<String, RequirementAssignmentData> nodesConnectedOut = + Objects.isNull(nestedTemplateConsolidationData) ? ArrayListMultimap.create() : nestedTemplateConsolidationData.getNodesConnectedOut(); + FileComputeConsolidationData nestedFileComputeConsolidationData = context.getConsolidationData().getComputeConsolidationData() + .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + if (Objects.isNull(nestedFileComputeConsolidationData)) { + return; + } + TypeComputeConsolidationData computeType = nestedFileComputeConsolidationData.getAllTypeComputeConsolidationData().iterator().next(); + if (Objects.isNull(computeType)) { + return; + } + String singleComputeId = computeType.getAllComputeNodeTemplateIds().iterator().next(); + if (Objects.nonNull(singleComputeId) && (Objects.nonNull(nestedTemplateConsolidationData))) { + updateRequirementInNestedNodeTemplate(serviceTemplate, nestedTemplateConsolidationData, singleComputeId, nodesConnectedOut); + } } - } - private void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> - unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - //Update requirements in the node template which pointing to the computes - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - updNodesConnectedInConnectivity(serviceTemplate, computeTemplateConsolidationData, - newComputeNodeTemplateId, context, false); - - String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData - .getNodeTemplateId()); - //Update requirements in the node template which pointing to the ports - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData - .getNodeTemplateId(), computeType, computeTemplateConsolidationData); - updNodesConnectedInConnectivity(serviceTemplate, portTemplateConsolidationData, - newPortNodeTemplateId, context, false); - } - - //Update requirements in the node template which pointing to the sub-interface - updateSubInterfaceNodesConnectedIn(serviceTemplate, unifiedCompositionData, - computeTemplateConsolidationData, computeType, context); - } - } - - private void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, - EntityConsolidationData entityConsolidationData, - String newNodeTemplateId, - TranslationContext context, - boolean isNested) { - Multimap<String, RequirementAssignmentData> nodesConnectedIn = - entityConsolidationData.getNodesConnectedIn(); + private void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + //Update requirements in the node template which pointing to the computes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + updNodesConnectedInConnectivity(serviceTemplate, computeTemplateConsolidationData, newComputeNodeTemplateId, context, false); + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + //Update requirements in the node template which pointing to the ports + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + updNodesConnectedInConnectivity(serviceTemplate, portTemplateConsolidationData, newPortNodeTemplateId, context, false); + } + //Update requirements in the node template which pointing to the sub-interface + updateSubInterfaceNodesConnectedIn(serviceTemplate, unifiedCompositionData, computeTemplateConsolidationData, computeType, context); + } + } + + private void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, + String newNodeTemplateId, TranslationContext context, boolean isNested) { + Multimap<String, RequirementAssignmentData> nodesConnectedIn = entityConsolidationData.getNodesConnectedIn(); if (nodesConnectedIn == null) { //No nodes connected in info return; } - for (String key : nodesConnectedIn.keySet()) { Collection<RequirementAssignmentData> requirementAssignmentDataList = nodesConnectedIn.get(key); for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { - RequirementAssignment requirementAssignment = requirementAssignmentData - .getRequirementAssignment(); - if (!requirementAssignment.getNode().equals(entityConsolidationData - .getNodeTemplateId())) { + RequirementAssignment requirementAssignment = requirementAssignmentData.getRequirementAssignment(); + if (!requirementAssignment.getNode().equals(entityConsolidationData.getNodeTemplateId())) { //The requirement assignment target node should be the one which we are handling in the + //consolidation object continue; } //Update the requirement assignment object in the original node template if (isNested) { - updateRequirementForNestedCompositionNodesConnectedIn(serviceTemplate, - requirementAssignmentData, newNodeTemplateId); + updateRequirementForNestedCompositionNodesConnectedIn(serviceTemplate, requirementAssignmentData, newNodeTemplateId); } else { - updateRequirementForNodesConnectedIn(serviceTemplate, requirementAssignmentData, - entityConsolidationData, key, newNodeTemplateId, context); + updateRequirementForNodesConnectedIn(serviceTemplate, requirementAssignmentData, entityConsolidationData, key, newNodeTemplateId, + context); } + } + } + } + + private void updateSubInterfaceNodesConnectedIn(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + ComputeTemplateConsolidationData computeTemplateConsolidationData, String computeType, + TranslationContext context) { + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, computeTemplateConsolidationData, + subInterfaceTemplateConsolidationData, context); + updNodesConnectedInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplateId, context, false); + } + } + + protected void updNestedCompositionNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + //Update requirements in the node template which pointing to the nested nodes + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional<String> newNestedNodeTemplateId = context + .getUnifiedNestedNodeTemplateId(serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); + newNestedNodeTemplateId.ifPresent( + newNestedNodeTemplateIdVal -> updNodesConnectedInConnectivity(serviceTemplate, nestedTemplateConsolidationData, + newNestedNodeTemplateIdVal, context, true)); + } + + private void updVolumeConnectivity(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + //Add requirements in the abstract node template for compute volumes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + Multimap<String, RequirementAssignmentData> computeVolumes = computeTemplateConsolidationData.getVolumes(); + if (computeVolumes != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, newComputeNodeTemplateId, computeVolumes, + context); + } + } + } + + private void updGroupsConnectivity(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + //Add requirements in the abstract node template for nodes connected in for computes + updGroupsConnectivity(serviceTemplate, computeTemplateConsolidationData, context); + //Add requirements in the abstract node template for nodes connected in for ports + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + updGroupsConnectivity(serviceTemplate, portTemplateConsolidationData, context); + } + //Add requirements in the abstract node template for nodes connected in for subInterface + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + updGroupsConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, context); + } + } + } + + private void updGroupsConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, TranslationContext context) { + List<String> groupIds = entityConsolidationData.getGroupIds(); + if (groupIds == null) { + return; + } + String oldNodeTemplateId = entityConsolidationData.getNodeTemplateId(); + String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, entityConsolidationData.getNodeTemplateId()); + Map<String, GroupDefinition> groups = serviceTemplate.getTopology_template().getGroups(); + if (groups == null) { + return; + } + for (String groupId : groupIds) { + GroupDefinition groupDefinition = groups.get(groupId); + if (groupDefinition == null) { + continue; + } + List<String> groupMembers = groupDefinition.getMembers(); + if (groupMembers.contains(oldNodeTemplateId)) { + //Replace the old node template id + groupMembers.remove(oldNodeTemplateId); + if (!groupMembers.contains(abstractNodeTemplateId)) { + //Add the abstract node template id if not already present + groupMembers.add(abstractNodeTemplateId); + } + } + } + } + + private void updOutputParamGetAttrInConnectivity(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedComposotionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + updOutputParamGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, + computeTemplateConsolidationData.getNodeTemplateId(), newComputeNodeTemplateId, context, false); + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + updOutputParamGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, portTemplateConsolidationData.getNodeTemplateId(), + newPortNodeTemplateId, context, false); + } + updateSubInterfaceOutputParamGetAttrIn(serviceTemplate, unifiedCompositionData, computeTemplateConsolidationData, computeType, context); + } + } + private void updateSubInterfaceOutputParamGetAttrIn(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + ComputeTemplateConsolidationData computeTemplateConsolidationData, String computeType, + TranslationContext context) { + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, computeTemplateConsolidationData, + subInterfaceTemplateConsolidationData, context); + updOutputParamGetAttrInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, + subInterfaceTemplateConsolidationData.getNodeTemplateId(), newSubInterfaceNodeTemplateId, context, false); + } + } + + private void updNodesGetAttrInConnectivity(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedComposotionDataList, + TranslationContext context) { + Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType = getAllConsolidationNodeTemplateIdAndType( + unifiedComposotionDataList); + for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + updNodeGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, computeTemplateConsolidationData.getNodeTemplateId(), + newComputeNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPotNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + updNodeGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, portTemplateConsolidationData.getNodeTemplateId(), + newPotNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); } + updateSubInterfaceNodesGetAttrIn(serviceTemplate, unifiedCompositionData, computeTemplateConsolidationData, computeType, + consolidationNodeTemplateIdAndType, context); } } - private void updateSubInterfaceNodesConnectedIn(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - String computeType, + private void updateSubInterfaceNodesGetAttrIn(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + ComputeTemplateConsolidationData computeTemplateConsolidationData, String computeType, + Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType, TranslationContext context) { - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, - computeTemplateConsolidationData, subInterfaceTemplateConsolidationData, context); - updNodesConnectedInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, - newSubInterfaceNodeTemplateId, context, false); - } - } - - protected void updNestedCompositionNodesConnectedInConnectivity( - ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData - .getNestedTemplateConsolidationData(); - //Update requirements in the node template which pointing to the nested nodes - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - Optional<String> newNestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId( - serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); - newNestedNodeTemplateId.ifPresent( - newNestedNodeTemplateIdVal -> updNodesConnectedInConnectivity(serviceTemplate, - nestedTemplateConsolidationData, - newNestedNodeTemplateIdVal, context, true)); - - } - - private void updVolumeConnectivity(ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> - unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - //Add requirements in the abstract node template for compute volumes - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - Multimap<String, RequirementAssignmentData> computeVolumes = - computeTemplateConsolidationData.getVolumes(); - if (computeVolumes != null) { - updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, - newComputeNodeTemplateId, computeVolumes, context); - } - } - } - - private void updGroupsConnectivity(ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> - unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - //Add requirements in the abstract node template for nodes connected in for computes - updGroupsConnectivity(serviceTemplate, computeTemplateConsolidationData, context); - - //Add requirements in the abstract node template for nodes connected in for ports - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - updGroupsConnectivity(serviceTemplate, portTemplateConsolidationData, context); - } - - //Add requirements in the abstract node template for nodes connected in for subInterface - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - updGroupsConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, context); - } - } - } - - private void updGroupsConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData - entityConsolidationData, TranslationContext context) { - List<String> groupIds = entityConsolidationData.getGroupIds(); - if (groupIds == null) { - return; - } - String oldNodeTemplateId = entityConsolidationData.getNodeTemplateId(); - String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId( - serviceTemplate, entityConsolidationData.getNodeTemplateId()); - Map<String, GroupDefinition> groups = serviceTemplate.getTopology_template().getGroups(); - if (groups == null) { - return; - } - for (String groupId : groupIds) { - GroupDefinition groupDefinition = groups.get(groupId); - if (groupDefinition == null) { - continue; - } - List<String> groupMembers = groupDefinition.getMembers(); - if (groupMembers.contains(oldNodeTemplateId)) { - //Replace the old node template id - groupMembers.remove(oldNodeTemplateId); - if (!groupMembers.contains(abstractNodeTemplateId)) { - //Add the abstract node template id if not already present - groupMembers.add(abstractNodeTemplateId); - } - } - } - } - - private void updOutputParamGetAttrInConnectivity( - ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedComposotionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - - updOutputParamGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, - computeTemplateConsolidationData.getNodeTemplateId(), newComputeNodeTemplateId, - context, false); - - String computeType = - getComputeTypeSuffix(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPortNodeTemplateId = - getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, - computeTemplateConsolidationData); - - updOutputParamGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, - portTemplateConsolidationData.getNodeTemplateId(), newPortNodeTemplateId, context, + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, computeTemplateConsolidationData, + subInterfaceTemplateConsolidationData, context); + updNodeGetAttrInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, + subInterfaceTemplateConsolidationData.getNodeTemplateId(), newSubInterfaceNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); - } - - updateSubInterfaceOutputParamGetAttrIn(serviceTemplate, unifiedCompositionData, - computeTemplateConsolidationData, computeType, context); - } - } - - private void updateSubInterfaceOutputParamGetAttrIn(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - String computeType, - TranslationContext context) { - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, - computeTemplateConsolidationData, subInterfaceTemplateConsolidationData, context); - updOutputParamGetAttrInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, - subInterfaceTemplateConsolidationData.getNodeTemplateId(), newSubInterfaceNodeTemplateId, context, - false); - } - } - - private void updNodesGetAttrInConnectivity( - ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> unifiedComposotionDataList, - TranslationContext context) { - Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType = - getAllConsolidationNodeTemplateIdAndType(unifiedComposotionDataList); - for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - - updNodeGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, - computeTemplateConsolidationData.getNodeTemplateId(), - newComputeNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); - - String computeType = - getComputeTypeSuffix(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPotNodeTemplateId = - getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, - computeTemplateConsolidationData); - - updNodeGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, - portTemplateConsolidationData.getNodeTemplateId(), - newPotNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); - } - - updateSubInterfaceNodesGetAttrIn(serviceTemplate, unifiedCompositionData, - computeTemplateConsolidationData, computeType, consolidationNodeTemplateIdAndType, context); - } - } - - private void updateSubInterfaceNodesGetAttrIn(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - String computeType, - Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType, - TranslationContext context) { - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, - computeTemplateConsolidationData, subInterfaceTemplateConsolidationData, context); - updNodeGetAttrInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, - subInterfaceTemplateConsolidationData.getNodeTemplateId(), - newSubInterfaceNodeTemplateId, context, - consolidationNodeTemplateIdAndType, false); - } - } - - protected void updNestedCompositionOutputParamGetAttrInConnectivity( - ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - if (Objects.isNull(nestedTemplateConsolidationData)) { - return; - } - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - Optional<String> newNestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId( - serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); - - newNestedNodeTemplateId.ifPresent( - newNestedNodeTemplateIdVal -> updOutputParamGetAttrInConnectivity(serviceTemplate, - nestedTemplateConsolidationData, nestedTemplateConsolidationData.getNodeTemplateId(), - newNestedNodeTemplateIdVal, context, true)); - } - - protected void updNestedCompositionNodesGetAttrInConnectivity( - ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - if (Objects.isNull(nestedTemplateConsolidationData)) { - return; - } - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - Optional<String> newNestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId( - serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); - - newNestedNodeTemplateId.ifPresent( - newNestedNodeTemplateIdVal -> updNodeGetAttrInConnectivity(serviceTemplate, - nestedTemplateConsolidationData, nestedTemplateConsolidationData.getNodeTemplateId(), - newNestedNodeTemplateIdVal, context, null, true)); - } - - private void updateRequirementForNodesConnectedIn( - ServiceTemplate serviceTemplate, - RequirementAssignmentData requirementAssignmentData, - EntityConsolidationData entityConsolidationData, - String originalNodeTemplateId, - String newNodeTemplateId, - TranslationContext context) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - RequirementAssignment requirementAssignment = requirementAssignmentData - .getRequirementAssignment(); - String newAbstractUnifiedNodeTemplateId = context.getUnifiedAbstractNodeTemplateId( - serviceTemplate, entityConsolidationData.getNodeTemplateId()); - NodeTemplate abstractUnifiedNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - newAbstractUnifiedNodeTemplateId); - Optional<String> newCapabilityId = getNewCapabilityForNodesConnectedIn(serviceTemplate, - abstractUnifiedNodeTemplate, requirementAssignment, newNodeTemplateId, context); - if (newCapabilityId.isPresent()) { - //Creating a copy of the requirement object and checking if it already exists in the - // original node template - RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( - requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); - NodeTemplate originalNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - originalNodeTemplateId); - requirementAssignmentCopy.setCapability(newCapabilityId.get()); - requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); - if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(originalNodeTemplate, - requirementAssignmentData.getRequirementId(), requirementAssignmentCopy)) { - //Update the existing requirement - requirementAssignmentData.getRequirementAssignment().setCapability(newCapabilityId - .get()); - requirementAssignmentData.getRequirementAssignment() - .setNode(newAbstractUnifiedNodeTemplateId); - } else { - //The updated requirement already exists in the node template so simply remove the - // current one - DataModelUtil.removeRequirementAssignment(originalNodeTemplate, requirementAssignmentData - .getRequirementId(), requirementAssignmentData.getRequirementAssignment()); - } - } - } - - private void updateRequirementForNestedCompositionNodesConnectedIn( - ServiceTemplate serviceTemplate, - RequirementAssignmentData requirementAssignmentData, - String newNodeTemplateId) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - String newAbstractUnifiedNodeTemplateId = newNodeTemplateId; - RequirementAssignment requirementAssignment = requirementAssignmentData - .getRequirementAssignment(); - //Creating a copy of the requirement object and checking if it already exists in the - // original node template - RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( + } + } + + protected void updNestedCompositionOutputParamGetAttrInConnectivity(ServiceTemplate serviceTemplate, + UnifiedCompositionData unifiedCompositionData, TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.isNull(nestedTemplateConsolidationData)) { + return; + } + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional<String> newNestedNodeTemplateId = context + .getUnifiedNestedNodeTemplateId(serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); + newNestedNodeTemplateId.ifPresent( + newNestedNodeTemplateIdVal -> updOutputParamGetAttrInConnectivity(serviceTemplate, nestedTemplateConsolidationData, + nestedTemplateConsolidationData.getNodeTemplateId(), newNestedNodeTemplateIdVal, context, true)); + } + + protected void updNestedCompositionNodesGetAttrInConnectivity(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.isNull(nestedTemplateConsolidationData)) { + return; + } + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional<String> newNestedNodeTemplateId = context + .getUnifiedNestedNodeTemplateId(serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); + newNestedNodeTemplateId.ifPresent(newNestedNodeTemplateIdVal -> updNodeGetAttrInConnectivity(serviceTemplate, nestedTemplateConsolidationData, + nestedTemplateConsolidationData.getNodeTemplateId(), newNestedNodeTemplateIdVal, context, null, true)); + } + + private void updateRequirementForNodesConnectedIn(ServiceTemplate serviceTemplate, RequirementAssignmentData requirementAssignmentData, + EntityConsolidationData entityConsolidationData, String originalNodeTemplateId, + String newNodeTemplateId, TranslationContext context) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + RequirementAssignment requirementAssignment = requirementAssignmentData.getRequirementAssignment(); + String newAbstractUnifiedNodeTemplateId = context + .getUnifiedAbstractNodeTemplateId(serviceTemplate, entityConsolidationData.getNodeTemplateId()); + NodeTemplate abstractUnifiedNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, newAbstractUnifiedNodeTemplateId); + Optional<String> newCapabilityId = getNewCapabilityForNodesConnectedIn(serviceTemplate, abstractUnifiedNodeTemplate, requirementAssignment, + newNodeTemplateId, context); + if (newCapabilityId.isPresent()) { + //Creating a copy of the requirement object and checking if it already exists in the + + // original node template + RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( + requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); + NodeTemplate originalNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, originalNodeTemplateId); + requirementAssignmentCopy.setCapability(newCapabilityId.get()); + requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); + if (!toscaAnalyzerService + .isRequirementExistInNodeTemplate(originalNodeTemplate, requirementAssignmentData.getRequirementId(), requirementAssignmentCopy)) { + //Update the existing requirement + requirementAssignmentData.getRequirementAssignment().setCapability(newCapabilityId.get()); + requirementAssignmentData.getRequirementAssignment().setNode(newAbstractUnifiedNodeTemplateId); + } else { + //The updated requirement already exists in the node template so simply remove the + + // current one + DataModelUtil.removeRequirementAssignment(originalNodeTemplate, requirementAssignmentData.getRequirementId(), + requirementAssignmentData.getRequirementAssignment()); + } + } + } + + private void updateRequirementForNestedCompositionNodesConnectedIn(ServiceTemplate serviceTemplate, + RequirementAssignmentData requirementAssignmentData, + String newNodeTemplateId) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + String newAbstractUnifiedNodeTemplateId = newNodeTemplateId; + RequirementAssignment requirementAssignment = requirementAssignmentData.getRequirementAssignment(); + //Creating a copy of the requirement object and checking if it already exists in the + + // original node template + RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); - NodeTemplate unifiedAbstractNestedNodeTemplate = DataModelUtil - .getNodeTemplate(serviceTemplate, newAbstractUnifiedNodeTemplateId); - requirementAssignmentCopy.setCapability(requirementAssignment.getCapability()); - requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); - if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(unifiedAbstractNestedNodeTemplate, - requirementAssignmentData.getRequirementId(), requirementAssignmentCopy)) { - //Update the existing requirement - requirementAssignmentData.getRequirementAssignment() - .setNode(newAbstractUnifiedNodeTemplateId); - } else { - //The updated requirement already exists in the node template so simply remove the - // current one - DataModelUtil.removeRequirementAssignment(unifiedAbstractNestedNodeTemplate, - requirementAssignmentData.getRequirementId(), requirementAssignmentData - .getRequirementAssignment()); - } - } - - private Optional<String> getNewCapabilityForNodesConnectedIn(ServiceTemplate serviceTemplate, - NodeTemplate unifiedNodeTemplate, - RequirementAssignment - requirementAssignment, - String newNodeTemplateId, - TranslationContext context) { - ServiceTemplate globalSubstitutionServiceTemplate = - HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); - Map<String, NodeType> nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); - String unifiedNodeTemplateType = unifiedNodeTemplate.getType(); - NodeType unifiedNodeType = nodeTypes.get(unifiedNodeTemplateType); - Map<String, CapabilityDefinition> abstractNodeTypeCapabilities = unifiedNodeType - .getCapabilities(); - for (Map.Entry<String, CapabilityDefinition> entry : abstractNodeTypeCapabilities.entrySet()) { - String capabilityId = entry.getKey(); - CapabilityDefinition capabilityDefinition = entry.getValue(); - String capabilityType = capabilityDefinition.getType(); - if (capabilityType.equals(requirementAssignment.getCapability()) - && capabilityId.endsWith(newNodeTemplateId)) { - //Matching capability type found..Check if the id ends with new node template id - return Optional.ofNullable(capabilityId); - } - } - return Optional.empty(); - } - - - private void updateRequirementInAbstractNodeTemplate(ServiceTemplate serviceTemplate, - EntityConsolidationData - entityConsolidationData, + NodeTemplate unifiedAbstractNestedNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, newAbstractUnifiedNodeTemplateId); + requirementAssignmentCopy.setCapability(requirementAssignment.getCapability()); + requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); + if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(unifiedAbstractNestedNodeTemplate, requirementAssignmentData.getRequirementId(), + requirementAssignmentCopy)) { + //Update the existing requirement + requirementAssignmentData.getRequirementAssignment().setNode(newAbstractUnifiedNodeTemplateId); + } else { + //The updated requirement already exists in the node template so simply remove the + + // current one + DataModelUtil.removeRequirementAssignment(unifiedAbstractNestedNodeTemplate, requirementAssignmentData.getRequirementId(), + requirementAssignmentData.getRequirementAssignment()); + } + } + + private Optional<String> getNewCapabilityForNodesConnectedIn(ServiceTemplate serviceTemplate, NodeTemplate unifiedNodeTemplate, + RequirementAssignment requirementAssignment, String newNodeTemplateId, + TranslationContext context) { + ServiceTemplate globalSubstitutionServiceTemplate = HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); + Map<String, NodeType> nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); + String unifiedNodeTemplateType = unifiedNodeTemplate.getType(); + NodeType unifiedNodeType = nodeTypes.get(unifiedNodeTemplateType); + Map<String, CapabilityDefinition> abstractNodeTypeCapabilities = unifiedNodeType.getCapabilities(); + for (Map.Entry<String, CapabilityDefinition> entry : abstractNodeTypeCapabilities.entrySet()) { + String capabilityId = entry.getKey(); + CapabilityDefinition capabilityDefinition = entry.getValue(); + String capabilityType = capabilityDefinition.getType(); + if (capabilityType.equals(requirementAssignment.getCapability()) && capabilityId.endsWith(newNodeTemplateId)) { + //Matching capability type found..Check if the id ends with new node template id + return Optional.ofNullable(capabilityId); + } + } + return Optional.empty(); + } + + private void updateRequirementInAbstractNodeTemplate(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, String newNodeTemplateId, - Multimap<String, RequirementAssignmentData> - requirementAssignmentDataMap, + Multimap<String, RequirementAssignmentData> requirementAssignmentDataMap, TranslationContext context) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); for (String key : requirementAssignmentDataMap.keySet()) { - String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId( - serviceTemplate, entityConsolidationData.getNodeTemplateId()); - NodeTemplate abstractNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - abstractNodeTemplateId); + String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, entityConsolidationData.getNodeTemplateId()); + NodeTemplate abstractNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, abstractNodeTemplateId); if (abstractNodeTemplate == null) { //The abstract node template is not found from id in the context return; @@ -1294,35 +970,28 @@ public class UnifiedCompositionService { Collection<RequirementAssignmentData> requirementAssignmentDataList = requirementAssignmentDataMap.get(key); for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { String oldRequirementId = requirementAssignmentData.getRequirementId(); - RequirementAssignment abstractRequirementAssignment = (RequirementAssignment) - getClonedObject(requirementAssignmentData.getRequirementAssignment(), - RequirementAssignment.class); + RequirementAssignment abstractRequirementAssignment = (RequirementAssignment) getClonedObject( + requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); String newRequirementId = oldRequirementId + "_" + newNodeTemplateId; //Check if the requirement is not already present in the list of requirements of the + // abstract node template - if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(abstractNodeTemplate, - newRequirementId, abstractRequirementAssignment)) { - DataModelUtil.addRequirementAssignment(abstractNodeTemplate, newRequirementId, - abstractRequirementAssignment); + if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(abstractNodeTemplate, newRequirementId, abstractRequirementAssignment)) { + DataModelUtil.addRequirementAssignment(abstractNodeTemplate, newRequirementId, abstractRequirementAssignment); //Update the volume relationship template if required - updateVolumeRelationshipTemplate(serviceTemplate, abstractRequirementAssignment - .getRelationship(), context); + updateVolumeRelationshipTemplate(serviceTemplate, abstractRequirementAssignment.getRelationship(), context); } } } } - private void updateRequirementInNestedNodeTemplate(ServiceTemplate serviceTemplate, - EntityConsolidationData entityConsolidationData, + private void updateRequirementInNestedNodeTemplate(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, String newNodeTemplateId, - Multimap<String, RequirementAssignmentData> - requirementAssignmentDataMap) { + Multimap<String, RequirementAssignmentData> requirementAssignmentDataMap) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - if (CommonUtil.isMultimapEmpty(requirementAssignmentDataMap)) { return; } - for (String key : requirementAssignmentDataMap.keySet()) { String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, nodeTemplateId); @@ -1333,2472 +1002,1817 @@ public class UnifiedCompositionService { Collection<RequirementAssignmentData> requirementAssignmentDataList = requirementAssignmentDataMap.get(key); for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { String oldRequirementId = requirementAssignmentData.getRequirementId(); - RequirementAssignment clonedRequirementAssignment = (RequirementAssignment) - getClonedObject(requirementAssignmentData.getRequirementAssignment(), - RequirementAssignment.class); + RequirementAssignment clonedRequirementAssignment = (RequirementAssignment) getClonedObject( + requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); String newRequirementId = oldRequirementId + "_" + newNodeTemplateId; //Check if the requirement is not already present in the list of requirements of the + // node template - if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(nodeTemplate, - newRequirementId, clonedRequirementAssignment)) { - DataModelUtil.removeRequirementAssignment(nodeTemplate, oldRequirementId, - requirementAssignmentData.getRequirementAssignment()); - DataModelUtil.addRequirementAssignment(nodeTemplate, newRequirementId, - clonedRequirementAssignment); + if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(nodeTemplate, newRequirementId, clonedRequirementAssignment)) { + DataModelUtil.removeRequirementAssignment(nodeTemplate, oldRequirementId, requirementAssignmentData.getRequirementAssignment()); + DataModelUtil.addRequirementAssignment(nodeTemplate, newRequirementId, clonedRequirementAssignment); } } } } - private void updNodeGetAttrInConnectivity( - ServiceTemplate serviceTemplate, - EntityConsolidationData entityConsolidationData, - String oldNodeTemplateId, String newNodeTemplateId, - TranslationContext context, - Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType, - boolean isNested) { - Map<String, List<GetAttrFuncData>> nodesGetAttrIn = entityConsolidationData.getNodesGetAttrIn(); - if (MapUtils.isEmpty(nodesGetAttrIn)) { - return; - } - - for (Map.Entry<String, List<GetAttrFuncData>> nodesGetAttrInEntry : nodesGetAttrIn.entrySet()) { - String sourceNodeTemplateId = nodesGetAttrInEntry.getKey(); - NodeTemplate sourceNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, sourceNodeTemplateId); - if (!isNested && consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { - continue; - } - List<GetAttrFuncData> getAttrFuncDataList = nodesGetAttrInEntry.getValue(); - for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { - Object propertyValue = - DataModelUtil.getPropertyValue(sourceNodeTemplate, getAttrFuncData.getFieldName()); - String newAttrName = null; - String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; - if (!isNested) { - newGetAttrAbstractNodeTemplateId = - context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); - newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData - .getAttributeName()); - } - List<List<Object>> getAttrFuncValueList = extractGetAttrFunction(propertyValue); - updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, - newAttrName, getAttrFuncValueList, isNested); - } - } - } - - private void updateGetAttrValue(String oldNodeTemplateId, GetAttrFuncData getAttrFuncData, - String newNodeTemplateId, String newAttrName, - List<List<Object>> getAttrFuncValueList, boolean isNested) { - for (List<Object> getAttrFuncValue : getAttrFuncValueList) { - if (oldNodeTemplateId.equals(getAttrFuncValue.get(0)) - && getAttrFuncData.getAttributeName().equals(getAttrFuncValue.get(1))) { - getAttrFuncValue.set(0, newNodeTemplateId); - if (!isNested) { - getAttrFuncValue.set(1, newAttrName); - } - } - } - } - - private String getTemplateName(String nodeTypeId, - Integer index) { - String computeType = getComputeTypeSuffix(nodeTypeId); - String templateName = "Nested_" + computeType; - if (Objects.nonNull(index)) { - templateName = templateName + "_" + index.toString(); - } - return templateName; - } - - private void updOutputParamGetAttrInConnectivity(ServiceTemplate serviceTemplate, - EntityConsolidationData entityConsolidationData, - String oldNodeTemplateId, - String newNodeTemplateId, - TranslationContext context, - boolean isNested) { - List<GetAttrFuncData> outputParametersGetAttrIn = - entityConsolidationData.getOutputParametersGetAttrIn(); - if (CollectionUtils.isEmpty(outputParametersGetAttrIn)) { - return; - } - for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { - Object outputParamValue = - DataModelUtil.getOuputParameter(serviceTemplate, getAttrFuncData.getFieldName()) - .getValue(); - String newAttrName = null; - String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; - if (!isNested) { - newGetAttrAbstractNodeTemplateId = - context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); - newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData - .getAttributeName()); - } - List<List<Object>> getAttrFuncValueList = extractGetAttrFunction(outputParamValue); - updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, - newAttrName, - getAttrFuncValueList, isNested); - } - - } - - private List<List<Object>> extractGetAttrFunction(Object valueObject) { - - List<List<Object>> getAttrValueList = new ArrayList<>(); - - if (valueObject instanceof Map) { - if (((Map) valueObject).containsKey(ToscaFunctions.GET_ATTRIBUTE.getFunctionName())) { - getAttrValueList.add( - (List<Object>) ((Map) valueObject).get(ToscaFunctions.GET_ATTRIBUTE.getFunctionName())); - } - - for (Object key : ((Map) valueObject).keySet()) { - getAttrValueList.addAll(extractGetAttrFunction(((Map) valueObject).get(key))); - } - - - } else if (valueObject instanceof List) { - for (Object valueEntity : (List) valueObject) { - getAttrValueList.addAll(extractGetAttrFunction(valueEntity)); - } - } - return getAttrValueList; - } - - private boolean isIncludeToscaFunc(Object valueObject, ToscaFunctions toscaFunction) { - if (valueObject instanceof Map) { - if (((Map) valueObject).containsKey(toscaFunction.getFunctionName())) { - return true; - } - - Set<Map.Entry<String, Object>> entries = ((Map<String, Object>) valueObject).entrySet(); - for (Map.Entry<String, Object> valueObjectEntry : entries) { - if (isIncludeToscaFunc(valueObjectEntry.getValue(), toscaFunction)) { - return true; - } - } - } else if (valueObject instanceof List) { - for (Object valueEntity : (List) valueObject) { - if (isIncludeToscaFunc(valueEntity, toscaFunction)) { - return true; - } - } - } - return false; - } - - private void createOutputParameters(UnifiedCompositionTo unifiedCompositionTo, - String computeNodeType) { - - createOutputParametersForCompute(unifiedCompositionTo.getServiceTemplate(), - unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getUnifiedCompositionDataList(), - unifiedCompositionTo.getContext()); - createOutputParameterForPorts(unifiedCompositionTo.getSubstitutionServiceTemplate(), - unifiedCompositionTo.getUnifiedCompositionDataList(), computeNodeType, unifiedCompositionTo.getContext()); - createOutputParameterForSubInterfaces(unifiedCompositionTo, computeNodeType); - } - - private void createOutputParameterForPorts( - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - String connectedComputeNodeType, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { - return; - } - - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPortNodeTemplateId = - getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), - connectedComputeNodeType, - unifiedCompositionData.getComputeTemplateConsolidationData()); - addOutputParameters(portTemplateConsolidationData, newPortNodeTemplateId, - substitutionServiceTemplate, unifiedCompositionDataList, context); - } - } - } - - private void createOutputParameterForSubInterfaces(UnifiedCompositionTo unifiedCompositionTo, - String connectedComputeNodeType) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionTo.getUnifiedCompositionDataList()) { - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - if (CollectionUtils.isEmpty(subInterfaceTemplateConsolidationDataList)) { - return; - } - - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(unifiedCompositionTo - .getServiceTemplate(), connectedComputeNodeType, unifiedCompositionData - .getComputeTemplateConsolidationData(), subInterfaceTemplateConsolidationData, - unifiedCompositionTo.getContext()); - addOutputParameters(subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplateId, - unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getUnifiedCompositionDataList(), - unifiedCompositionTo.getContext()); - } - } - } - - private void createOutputParametersForCompute( - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> - unifiedCompositionDataList, - TranslationContext context) { - List<EntityConsolidationData> computeConsolidationDataList = - getComputeConsolidationDataList(unifiedCompositionDataList); - - for (EntityConsolidationData computeTemplateConsolidationData : computeConsolidationDataList) { - String newComputeNodeTemplateId = - getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - addOutputParameters(computeTemplateConsolidationData, newComputeNodeTemplateId, - substitutionServiceTemplate, unifiedCompositionDataList, context); - } - } - - private void addOutputParameters(EntityConsolidationData entityConsolidationData, - String newNodeTemplateId, - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - handleNodesGetAttrIn(entityConsolidationData, newNodeTemplateId, substitutionServiceTemplate, - unifiedCompositionDataList, context); - - handleOutputParamGetAttrIn(entityConsolidationData, newNodeTemplateId, - substitutionServiceTemplate, context); - } - - private void handleOutputParamGetAttrIn(EntityConsolidationData entityConsolidationData, - String newNodeTemplateId, - ServiceTemplate substitutionServiceTemplate, - TranslationContext context) { - List<GetAttrFuncData> outputParametersGetAttrIn = - entityConsolidationData.getOutputParametersGetAttrIn(); - if (!CollectionUtils.isEmpty(outputParametersGetAttrIn)) { - for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { - createAndAddOutputParameter(newNodeTemplateId, - substitutionServiceTemplate, getAttrFuncData, context); - } - } - } - - private void handleNodesGetAttrIn(EntityConsolidationData entityConsolidationData, - String newNodeTemplateId, - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - Map<String, List<GetAttrFuncData>> getAttrIn = entityConsolidationData.getNodesGetAttrIn(); - if (MapUtils.isEmpty(getAttrIn)) { - return; - } - Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType = - getAllConsolidationNodeTemplateIdAndType(unifiedCompositionDataList); - for (Map.Entry<String, List<GetAttrFuncData>> getAttrInEntry : getAttrIn.entrySet()) { - String sourceNodeTemplateId = getAttrInEntry.getKey(); - if (!consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { - List<GetAttrFuncData> getAttrFuncDataList = getAttrInEntry.getValue(); - for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { - createAndAddOutputParameter(newNodeTemplateId, - substitutionServiceTemplate, getAttrFuncData, context); - } - } - } - } - - private void createAndAddOutputParameter(String newNodeTemplateId, - ServiceTemplate substitutionServiceTemplate, - GetAttrFuncData getAttrFuncData, - TranslationContext context) { - Map<String, List<Object>> parameterValue = new HashMap<>(); - List<Object> valueList = new ArrayList<>(); - valueList.add(newNodeTemplateId); - valueList.add(getAttrFuncData.getAttributeName()); - parameterValue.put(ToscaFunctions.GET_ATTRIBUTE.getFunctionName(), valueList); - ParameterDefinition outputParameter = new ParameterDefinition(); - outputParameter.setValue(parameterValue); - setOutputParameterType(substitutionServiceTemplate, newNodeTemplateId, getAttrFuncData - .getAttributeName(), outputParameter, context); - DataModelUtil.addOutputParameterToTopologyTemplate(substitutionServiceTemplate, - getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData.getAttributeName()), - outputParameter); - } - - private void setOutputParameterType(ServiceTemplate substitutionServiceTemplate, - String newNodeTemplateId, - String outputParameterName, - ParameterDefinition outputParameter, - TranslationContext context) { - NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(substitutionServiceTemplate, - newNodeTemplateId); - //Get the type and entry schema of the output parameter from the node type flat hierarchy - String outputParameterType; - EntrySchema outputParameterEntrySchema; - NodeType nodeTypeWithFlatHierarchy = - HeatToToscaUtil.getNodeTypeWithFlatHierarchy(nodeTemplate.getType(), - substitutionServiceTemplate, context); - //Check if the parameter is present in the attributes - AttributeDefinition outputParameterDefinitionFromAttributes = - getOutputParameterDefinitionFromAttributes(nodeTypeWithFlatHierarchy, outputParameterName); - if (Objects.nonNull(outputParameterDefinitionFromAttributes)) { - outputParameterType = outputParameterDefinitionFromAttributes.getType(); - outputParameterEntrySchema = outputParameterDefinitionFromAttributes.getEntry_schema(); - } else { - //If the below fails due to null pointer then we need to check if the heatToToscaMapping - // properties and global types are in sync. Ideally the parameter should be found in either - // properties or attributes collected from global types - PropertyDefinition outputParameterDefinitionFromProperties = - nodeTypeWithFlatHierarchy.getProperties().get(outputParameterName); - outputParameterType = outputParameterDefinitionFromProperties.getType(); - outputParameterEntrySchema = outputParameterDefinitionFromProperties.getEntry_schema(); - } - //Set the type and entry schema for the output param obtained from the node type hierarchy - outputParameter.setType(outputParameterType); - outputParameter.setEntry_schema(outputParameterEntrySchema); - } - - private AttributeDefinition getOutputParameterDefinitionFromAttributes(NodeType - nodeTypeWithFlatHierarchy, - String outputParameterName) { - AttributeDefinition outputParameterDefinition = null; - if ((Objects.nonNull(nodeTypeWithFlatHierarchy.getAttributes())) - && (nodeTypeWithFlatHierarchy.getAttributes().containsKey(outputParameterName))) { - outputParameterDefinition = - nodeTypeWithFlatHierarchy.getAttributes().get(outputParameterName); - } - return outputParameterDefinition; - } - - private String getNewSubstitutionOutputParameterId(String newNodeTemplateId, - String attributeName) { - return newNodeTemplateId + "_" + attributeName; - } - - private void addUnifiedSubstitionData(TranslationContext context, ServiceTemplate - serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, String - substituteNodeTemplateId) { - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - //Add compute node template mapping information - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - String computeNodeTemplateId = computeTemplateConsolidationData.getNodeTemplateId(); - context.addUnifiedSubstitutionData(serviceTemplateFileName, computeNodeTemplateId, - substituteNodeTemplateId); - //Add Port template mapping information - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - - if (CollectionUtils.isNotEmpty(portTemplateConsolidationDataList)) { - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String oldPortNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); - context.addUnifiedSubstitutionData(serviceTemplateFileName, oldPortNodeTemplateId, - substituteNodeTemplateId); - } - } - //Add Sub-interface template mapping information - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - if (CollectionUtils.isNotEmpty(subInterfaceTemplateConsolidationDataList)) { - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - context.addUnifiedSubstitutionData(serviceTemplateFileName, - subInterfaceTemplateConsolidationData.getNodeTemplateId(), substituteNodeTemplateId); - } - } - } - } - - private void addIndexValueProperty(NodeTemplate nodeTemplate) { - List<String> indexValueGetPropertyValue = new ArrayList<>(); - indexValueGetPropertyValue.add(ToscaConstants.MODELABLE_ENTITY_NAME_SELF); - indexValueGetPropertyValue.add(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); - indexValueGetPropertyValue.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); - - Map<String, Object> indexPropertyValue = new HashMap<>(); - Map<String, Object> properties = nodeTemplate.getProperties(); - indexPropertyValue.put(ToscaFunctions.GET_PROPERTY.getFunctionName(), - indexValueGetPropertyValue); - properties.put(ToscaConstants.INDEX_VALUE_PROPERTY_NAME, - indexPropertyValue); - nodeTemplate.setProperties(properties); - } - - private String getSubstituteNodeTemplateId(String nodeTypeId, - Integer index) { - String nodeTemplateId = ABSTRACT_NODE_TEMPLATE_ID_PREFIX + DataModelUtil - .getNamespaceSuffix(nodeTypeId); - if (Objects.nonNull(index)) { - nodeTemplateId = nodeTemplateId + "_" + index.toString(); - } - return nodeTemplateId; - } - - /** - * Gets substitution node type id. - * - * @param serviceTemplate the service template - * @param unifiedCompositionData the unified composition data - * @param index the index - * @return the substitution node type id - */ - public String getSubstitutionNodeTypeId(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - Integer index, - TranslationContext context) { - String computeNodeTemplateId = - unifiedCompositionData.getComputeTemplateConsolidationData().getNodeTemplateId(); - NodeTemplate computeNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); - String computeType = computeNodeTemplate.getType(); - String globalSTName = ToscaUtil.getServiceTemplateFileName(Constants - .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - - String nodeTypeId = ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX - + DataModelUtil.getNamespaceSuffix(getIndexedGlobalNodeTypeId(computeType, context)); - - context.updateUsedTimesForNestedComputeNodeType(globalSTName, computeType); - - if (Objects.nonNull(index)) { - nodeTypeId = nodeTypeId + "_" + index.toString(); - } - return nodeTypeId; - } - - private NodeType handleSubstitutionGlobalNodeType(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - TranslationContext context, - String substitutionNodeTypeId) { - NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() - .createInitSubstitutionNodeType(substitutionServiceTemplate, - ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); - ServiceTemplate globalSubstitutionServiceTemplate = - HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); - DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeId, - substitutionNodeType); - - return substitutionNodeType; - } - - private void handlePorts(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - String connectedComputeNodeType, - TranslationContext context) { - - if (unifiedCompositionDataList.size() > 1) { - handleConsolidationPorts(serviceTemplate, substitutionServiceTemplate, - unifiedCompositionDataList, connectedComputeNodeType, context); - } else { - handleSinglePorts(serviceTemplate, substitutionServiceTemplate, connectedComputeNodeType, - unifiedCompositionDataList, context); - } - } - - private void handleSinglePorts(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - String connectedComputeNodeType, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - UnifiedCompositionData unifiedCompositionData = unifiedCompositionDataList.get(0); - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { - return; - } - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - List<EntityConsolidationData> portConsolidationDataList = new ArrayList<>(); - portConsolidationDataList.add(portTemplateConsolidationData); - handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, - portConsolidationDataList, connectedComputeNodeType, - unifiedCompositionData.getComputeTemplateConsolidationData(), - unifiedCompositionDataList, context); - } - } - - private void handleConsolidationPorts(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - String connectedComputeNodeType, - TranslationContext context) { - Map<String, List<String>> portIdsPerPortType = - UnifiedCompositionUtil.collectAllPortsOfEachTypeFromComputes(unifiedCompositionDataList); + private void updNodeGetAttrInConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, + String oldNodeTemplateId, String newNodeTemplateId, TranslationContext context, + Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType, boolean isNested) { + Map<String, List<GetAttrFuncData>> nodesGetAttrIn = entityConsolidationData.getNodesGetAttrIn(); + if (MapUtils.isEmpty(nodesGetAttrIn)) { + return; + } + for (Map.Entry<String, List<GetAttrFuncData>> nodesGetAttrInEntry : nodesGetAttrIn.entrySet()) { + String sourceNodeTemplateId = nodesGetAttrInEntry.getKey(); + NodeTemplate sourceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, sourceNodeTemplateId); + if (!isNested && consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { + continue; + } + List<GetAttrFuncData> getAttrFuncDataList = nodesGetAttrInEntry.getValue(); + for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { + Object propertyValue = DataModelUtil.getPropertyValue(sourceNodeTemplate, getAttrFuncData.getFieldName()); + String newAttrName = null; + String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; + if (!isNested) { + newGetAttrAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); + newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData.getAttributeName()); + } + List<List<Object>> getAttrFuncValueList = extractGetAttrFunction(propertyValue); + updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, newAttrName, getAttrFuncValueList, isNested); + } + } + } - for (Map.Entry<String, List<String>> portIdsPerPortTypeEntry : portIdsPerPortType.entrySet()) { - List<EntityConsolidationData> portTemplateConsolidationDataList = - getPortConsolidationDataList(portIdsPerPortTypeEntry.getValue(), unifiedCompositionDataList); + private void updateGetAttrValue(String oldNodeTemplateId, GetAttrFuncData getAttrFuncData, String newNodeTemplateId, String newAttrName, + List<List<Object>> getAttrFuncValueList, boolean isNested) { + for (List<Object> getAttrFuncValue : getAttrFuncValueList) { + if (oldNodeTemplateId.equals(getAttrFuncValue.get(0)) && getAttrFuncData.getAttributeName().equals(getAttrFuncValue.get(1))) { + getAttrFuncValue.set(0, newNodeTemplateId); + if (!isNested) { + getAttrFuncValue.set(1, newAttrName); + } + } + } + } + + private String getTemplateName(String nodeTypeId, Integer index) { + String computeType = getComputeTypeSuffix(nodeTypeId); + String templateName = "Nested_" + computeType; + if (Objects.nonNull(index)) { + templateName = templateName + "_" + index.toString(); + } + return templateName; + } + + private void updOutputParamGetAttrInConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, + String oldNodeTemplateId, String newNodeTemplateId, TranslationContext context, + boolean isNested) { + List<GetAttrFuncData> outputParametersGetAttrIn = entityConsolidationData.getOutputParametersGetAttrIn(); + if (CollectionUtils.isEmpty(outputParametersGetAttrIn)) { + return; + } + for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { + Object outputParamValue = DataModelUtil.getOuputParameter(serviceTemplate, getAttrFuncData.getFieldName()).getValue(); + String newAttrName = null; + String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; + if (!isNested) { + newGetAttrAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); + newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData.getAttributeName()); + } + List<List<Object>> getAttrFuncValueList = extractGetAttrFunction(outputParamValue); + updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, newAttrName, getAttrFuncValueList, isNested); + } + } + + private List<List<Object>> extractGetAttrFunction(Object valueObject) { + List<List<Object>> getAttrValueList = new ArrayList<>(); + if (valueObject instanceof Map) { + if (((Map) valueObject).containsKey(ToscaFunctions.GET_ATTRIBUTE.getFunctionName())) { + getAttrValueList.add((List<Object>) ((Map) valueObject).get(ToscaFunctions.GET_ATTRIBUTE.getFunctionName())); + } + for (Object key : ((Map) valueObject).keySet()) { + getAttrValueList.addAll(extractGetAttrFunction(((Map) valueObject).get(key))); + } + } else if (valueObject instanceof List) { + for (Object valueEntity : (List) valueObject) { + getAttrValueList.addAll(extractGetAttrFunction(valueEntity)); + } + } + return getAttrValueList; + } + + private boolean isIncludeToscaFunc(Object valueObject, ToscaFunctions toscaFunction) { + if (valueObject instanceof Map) { + if (((Map) valueObject).containsKey(toscaFunction.getFunctionName())) { + return true; + } + Set<Map.Entry<String, Object>> entries = ((Map<String, Object>) valueObject).entrySet(); + for (Map.Entry<String, Object> valueObjectEntry : entries) { + if (isIncludeToscaFunc(valueObjectEntry.getValue(), toscaFunction)) { + return true; + } + } + } else if (valueObject instanceof List) { + for (Object valueEntity : (List) valueObject) { + if (isIncludeToscaFunc(valueEntity, toscaFunction)) { + return true; + } + } + } + return false; + } + + private void createOutputParameters(UnifiedCompositionTo unifiedCompositionTo, String computeNodeType) { + createOutputParametersForCompute(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getSubstitutionServiceTemplate(), + unifiedCompositionTo.getUnifiedCompositionDataList(), unifiedCompositionTo.getContext()); + createOutputParameterForPorts(unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getUnifiedCompositionDataList(), + computeNodeType, unifiedCompositionTo.getContext()); + createOutputParameterForSubInterfaces(unifiedCompositionTo, computeNodeType); + } + + private void createOutputParameterForPorts(ServiceTemplate substitutionServiceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + String connectedComputeNodeType, TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { - continue; + return; } + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), connectedComputeNodeType, + unifiedCompositionData.getComputeTemplateConsolidationData()); + addOutputParameters(portTemplateConsolidationData, newPortNodeTemplateId, substitutionServiceTemplate, unifiedCompositionDataList, + context); + } + } + } - handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, portTemplateConsolidationDataList, - connectedComputeNodeType, unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(), - unifiedCompositionDataList, context); + private void createOutputParameterForSubInterfaces(UnifiedCompositionTo unifiedCompositionTo, String connectedComputeNodeType) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionTo.getUnifiedCompositionDataList()) { + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + if (CollectionUtils.isEmpty(subInterfaceTemplateConsolidationDataList)) { + return; + } + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), + connectedComputeNodeType, unifiedCompositionData.getComputeTemplateConsolidationData(), subInterfaceTemplateConsolidationData, + unifiedCompositionTo.getContext()); + addOutputParameters(subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplateId, + unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getUnifiedCompositionDataList(), + unifiedCompositionTo.getContext()); + } } } - private void handlePortNodeTemplate( - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List<EntityConsolidationData> portTemplateConsolidationDataList, - String connectedComputeNodeType, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - EntityConsolidationData portTemplateConsolidationData = - portTemplateConsolidationDataList.get(0); - NodeTemplate newPortNodeTemplate = getNodeTemplate( - portTemplateConsolidationData.getNodeTemplateId(), serviceTemplate, context).clone(); + private void createOutputParametersForCompute(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + List<EntityConsolidationData> computeConsolidationDataList = getComputeConsolidationDataList(unifiedCompositionDataList); + for (EntityConsolidationData computeTemplateConsolidationData : computeConsolidationDataList) { + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + addOutputParameters(computeTemplateConsolidationData, newComputeNodeTemplateId, substitutionServiceTemplate, unifiedCompositionDataList, + context); + } + } - removeConnectivityOut(portTemplateConsolidationData, newPortNodeTemplate); - handleProperties(serviceTemplate, newPortNodeTemplate, - substitutionServiceTemplate, UnifiedCompositionEntity.PORT, - portTemplateConsolidationDataList, computeTemplateConsolidationData, - unifiedCompositionDataList, context); + private void addOutputParameters(EntityConsolidationData entityConsolidationData, String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context) { + handleNodesGetAttrIn(entityConsolidationData, newNodeTemplateId, substitutionServiceTemplate, unifiedCompositionDataList, context); + handleOutputParamGetAttrIn(entityConsolidationData, newNodeTemplateId, substitutionServiceTemplate, context); + } - //Add subinterface_indicator property to PORT - portTemplateConsolidationDataList.forEach(entity -> - addPortSubInterfaceIndicatorProperty(newPortNodeTemplate.getProperties(), entity)); + private void handleOutputParamGetAttrIn(EntityConsolidationData entityConsolidationData, String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate, TranslationContext context) { + List<GetAttrFuncData> outputParametersGetAttrIn = entityConsolidationData.getOutputParametersGetAttrIn(); + if (!CollectionUtils.isEmpty(outputParametersGetAttrIn)) { + for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { + createAndAddOutputParameter(newNodeTemplateId, substitutionServiceTemplate, getAttrFuncData, context); + } + } + } - String newPortNodeTemplateId = - getNewPortNodeTemplateId(portTemplateConsolidationData - .getNodeTemplateId(), connectedComputeNodeType, - computeTemplateConsolidationData); - //Update requirements for relationships between the consolidation entities - handleConsolidationEntitiesRequirementConnectivity(newPortNodeTemplate, - serviceTemplate, context); - DataModelUtil.addNodeTemplate(substitutionServiceTemplate, newPortNodeTemplateId, - newPortNodeTemplate); - - //Add the node template mapping in the context for handling requirement updation - for (EntityConsolidationData data : portTemplateConsolidationDataList) { - String newPortTemplateId = getNewPortNodeTemplateId(data.getNodeTemplateId(), - connectedComputeNodeType, computeTemplateConsolidationData); - context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), data.getNodeTemplateId(), - newPortTemplateId); - } - - } - - private void handleSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { - if (unifiedCompositionTo.getUnifiedCompositionDataList().size() > 1) { - handleConsolidationSubInterfaces(unifiedCompositionTo); - } else { - handleSingleSubInterfaces(unifiedCompositionTo); - } - } - - private void handleSingleSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { - UnifiedCompositionData unifiedCompositionData = unifiedCompositionTo.getUnifiedCompositionDataList().get(0); - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - List<SubInterfaceTemplateConsolidationData> subInterfaceDataList = new ArrayList<>(); - subInterfaceDataList.add(subInterfaceTemplateConsolidationData); - createSubInterfaceSubstitutionNodeTemplate(unifiedCompositionTo, subInterfaceDataList); - } - } + private void handleNodesGetAttrIn(EntityConsolidationData entityConsolidationData, String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context) { + Map<String, List<GetAttrFuncData>> getAttrIn = entityConsolidationData.getNodesGetAttrIn(); + if (MapUtils.isEmpty(getAttrIn)) { + return; + } + Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType = getAllConsolidationNodeTemplateIdAndType( + unifiedCompositionDataList); + for (Map.Entry<String, List<GetAttrFuncData>> getAttrInEntry : getAttrIn.entrySet()) { + String sourceNodeTemplateId = getAttrInEntry.getKey(); + if (!consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { + List<GetAttrFuncData> getAttrFuncDataList = getAttrInEntry.getValue(); + for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { + createAndAddOutputParameter(newNodeTemplateId, substitutionServiceTemplate, getAttrFuncData, context); + } + } + } + } - private void handleConsolidationSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { - Map<String, List<String>> portIdsPerPortType = - UnifiedCompositionUtil.collectAllPortsOfEachTypeFromComputes( - unifiedCompositionTo.getUnifiedCompositionDataList()); + private void createAndAddOutputParameter(String newNodeTemplateId, ServiceTemplate substitutionServiceTemplate, GetAttrFuncData getAttrFuncData, + TranslationContext context) { + Map<String, List<Object>> parameterValue = new HashMap<>(); + List<Object> valueList = new ArrayList<>(); + valueList.add(newNodeTemplateId); + valueList.add(getAttrFuncData.getAttributeName()); + parameterValue.put(ToscaFunctions.GET_ATTRIBUTE.getFunctionName(), valueList); + ParameterDefinition outputParameter = new ParameterDefinition(); + outputParameter.setValue(parameterValue); + setOutputParameterType(substitutionServiceTemplate, newNodeTemplateId, getAttrFuncData.getAttributeName(), outputParameter, context); + DataModelUtil.addOutputParameterToTopologyTemplate(substitutionServiceTemplate, + getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData.getAttributeName()), outputParameter); + } + + private void setOutputParameterType(ServiceTemplate substitutionServiceTemplate, String newNodeTemplateId, String outputParameterName, + ParameterDefinition outputParameter, TranslationContext context) { + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(substitutionServiceTemplate, newNodeTemplateId); + //Get the type and entry schema of the output parameter from the node type flat hierarchy + String outputParameterType; + EntrySchema outputParameterEntrySchema; + NodeType nodeTypeWithFlatHierarchy = HeatToToscaUtil + .getNodeTypeWithFlatHierarchy(nodeTemplate.getType(), substitutionServiceTemplate, context); + //Check if the parameter is present in the attributes + AttributeDefinition outputParameterDefinitionFromAttributes = getOutputParameterDefinitionFromAttributes(nodeTypeWithFlatHierarchy, + outputParameterName); + if (Objects.nonNull(outputParameterDefinitionFromAttributes)) { + outputParameterType = outputParameterDefinitionFromAttributes.getType(); + outputParameterEntrySchema = outputParameterDefinitionFromAttributes.getEntry_schema(); + } else { + //If the below fails due to null pointer then we need to check if the heatToToscaMapping + + // properties and global types are in sync. Ideally the parameter should be found in either + + // properties or attributes collected from global types + PropertyDefinition outputParameterDefinitionFromProperties = nodeTypeWithFlatHierarchy.getProperties().get(outputParameterName); + outputParameterType = outputParameterDefinitionFromProperties.getType(); + outputParameterEntrySchema = outputParameterDefinitionFromProperties.getEntry_schema(); + } + //Set the type and entry schema for the output param obtained from the node type hierarchy + outputParameter.setType(outputParameterType); + outputParameter.setEntry_schema(outputParameterEntrySchema); + } + private AttributeDefinition getOutputParameterDefinitionFromAttributes(NodeType nodeTypeWithFlatHierarchy, String outputParameterName) { + AttributeDefinition outputParameterDefinition = null; + if ((Objects.nonNull(nodeTypeWithFlatHierarchy.getAttributes())) && (nodeTypeWithFlatHierarchy.getAttributes() + .containsKey(outputParameterName))) { + outputParameterDefinition = nodeTypeWithFlatHierarchy.getAttributes().get(outputParameterName); + } + return outputParameterDefinition; + } + + private String getNewSubstitutionOutputParameterId(String newNodeTemplateId, String attributeName) { + return newNodeTemplateId + "_" + attributeName; + } + + private void addUnifiedSubstitionData(TranslationContext context, ServiceTemplate serviceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, String substituteNodeTemplateId) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + //Add compute node template mapping information + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + String computeNodeTemplateId = computeTemplateConsolidationData.getNodeTemplateId(); + context.addUnifiedSubstitutionData(serviceTemplateFileName, computeNodeTemplateId, substituteNodeTemplateId); + //Add Port template mapping information + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + if (CollectionUtils.isNotEmpty(portTemplateConsolidationDataList)) { + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String oldPortNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); + context.addUnifiedSubstitutionData(serviceTemplateFileName, oldPortNodeTemplateId, substituteNodeTemplateId); + } + } + //Add Sub-interface template mapping information + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + if (CollectionUtils.isNotEmpty(subInterfaceTemplateConsolidationDataList)) { + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + context.addUnifiedSubstitutionData(serviceTemplateFileName, subInterfaceTemplateConsolidationData.getNodeTemplateId(), + substituteNodeTemplateId); + } + } + } + } + + private void addIndexValueProperty(NodeTemplate nodeTemplate) { + List<String> indexValueGetPropertyValue = new ArrayList<>(); + indexValueGetPropertyValue.add(ToscaConstants.MODELABLE_ENTITY_NAME_SELF); + indexValueGetPropertyValue.add(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + indexValueGetPropertyValue.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); + Map<String, Object> indexPropertyValue = new HashMap<>(); + Map<String, Object> properties = nodeTemplate.getProperties(); + indexPropertyValue.put(ToscaFunctions.GET_PROPERTY.getFunctionName(), indexValueGetPropertyValue); + properties.put(ToscaConstants.INDEX_VALUE_PROPERTY_NAME, indexPropertyValue); + nodeTemplate.setProperties(properties); + } + + private String getSubstituteNodeTemplateId(String nodeTypeId, Integer index) { + String nodeTemplateId = ABSTRACT_NODE_TEMPLATE_ID_PREFIX + DataModelUtil.getNamespaceSuffix(nodeTypeId); + if (Objects.nonNull(index)) { + nodeTemplateId = nodeTemplateId + "_" + index.toString(); + } + return nodeTemplateId; + } + + /** + * Gets substitution node type id. + * + * @param serviceTemplate the service template + * @param unifiedCompositionData the unified composition data + * @param index the index + * @return the substitution node type id + */ + public String getSubstitutionNodeTypeId(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, Integer index, + TranslationContext context) { + String computeNodeTemplateId = unifiedCompositionData.getComputeTemplateConsolidationData().getNodeTemplateId(); + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); + String computeType = computeNodeTemplate.getType(); + String globalSTName = ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + String nodeTypeId = + ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + DataModelUtil.getNamespaceSuffix(getIndexedGlobalNodeTypeId(computeType, context)); + context.updateUsedTimesForNestedComputeNodeType(globalSTName, computeType); + if (Objects.nonNull(index)) { + nodeTypeId = nodeTypeId + "_" + index.toString(); + } + return nodeTypeId; + } + + private NodeType handleSubstitutionGlobalNodeType(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + TranslationContext context, String substitutionNodeTypeId) { + NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() + .createInitSubstitutionNodeType(substitutionServiceTemplate, ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); + ServiceTemplate globalSubstitutionServiceTemplate = HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); + DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeId, substitutionNodeType); + return substitutionNodeType; + } + + private void handlePorts(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, String connectedComputeNodeType, TranslationContext context) { + if (unifiedCompositionDataList.size() > 1) { + handleConsolidationPorts(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, connectedComputeNodeType, context); + } else { + handleSinglePorts(serviceTemplate, substitutionServiceTemplate, connectedComputeNodeType, unifiedCompositionDataList, context); + } + } + + private void handleSinglePorts(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, String connectedComputeNodeType, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + UnifiedCompositionData unifiedCompositionData = unifiedCompositionDataList.get(0); + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { + return; + } + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + List<EntityConsolidationData> portConsolidationDataList = new ArrayList<>(); + portConsolidationDataList.add(portTemplateConsolidationData); + handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, portConsolidationDataList, connectedComputeNodeType, + unifiedCompositionData.getComputeTemplateConsolidationData(), unifiedCompositionDataList, context); + } + } + + private void handleConsolidationPorts(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, String connectedComputeNodeType, + TranslationContext context) { + Map<String, List<String>> portIdsPerPortType = UnifiedCompositionUtil.collectAllPortsOfEachTypeFromComputes(unifiedCompositionDataList); for (Map.Entry<String, List<String>> portIdsPerPortTypeEntry : portIdsPerPortType.entrySet()) { - List<EntityConsolidationData> portEntityConsolidationDataList = - getPortConsolidationDataList(portIdsPerPortTypeEntry.getValue(), - unifiedCompositionTo.getUnifiedCompositionDataList()); - if (CollectionUtils.isEmpty(portEntityConsolidationDataList)) { + List<EntityConsolidationData> portTemplateConsolidationDataList = getPortConsolidationDataList(portIdsPerPortTypeEntry.getValue(), + unifiedCompositionDataList); + if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { continue; } + handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, portTemplateConsolidationDataList, connectedComputeNodeType, + unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(), unifiedCompositionDataList, context); + } + } - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - portEntityConsolidationDataList.stream().map(data -> (PortTemplateConsolidationData) data) - .collect(Collectors.toList()); + private void handlePortNodeTemplate(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List<EntityConsolidationData> portTemplateConsolidationDataList, String connectedComputeNodeType, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + EntityConsolidationData portTemplateConsolidationData = portTemplateConsolidationDataList.get(0); + NodeTemplate newPortNodeTemplate = getNodeTemplate(portTemplateConsolidationData.getNodeTemplateId(), serviceTemplate, context).clone(); + removeConnectivityOut(portTemplateConsolidationData, newPortNodeTemplate); + handleProperties(serviceTemplate, newPortNodeTemplate, substitutionServiceTemplate, UnifiedCompositionEntity.PORT, + portTemplateConsolidationDataList, computeTemplateConsolidationData, unifiedCompositionDataList, context); + //Add subinterface_indicator property to PORT + portTemplateConsolidationDataList.forEach(entity -> addPortSubInterfaceIndicatorProperty(newPortNodeTemplate.getProperties(), entity)); + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), connectedComputeNodeType, + computeTemplateConsolidationData); + //Update requirements for relationships between the consolidation entities + handleConsolidationEntitiesRequirementConnectivity(newPortNodeTemplate, serviceTemplate, context); + DataModelUtil.addNodeTemplate(substitutionServiceTemplate, newPortNodeTemplateId, newPortNodeTemplate); + //Add the node template mapping in the context for handling requirement updation + for (EntityConsolidationData data : portTemplateConsolidationDataList) { + String newPortTemplateId = getNewPortNodeTemplateId(data.getNodeTemplateId(), connectedComputeNodeType, computeTemplateConsolidationData); + context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + data.getNodeTemplateId(), newPortTemplateId); + } + } + + private void handleSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { + if (unifiedCompositionTo.getUnifiedCompositionDataList().size() > 1) { + handleConsolidationSubInterfaces(unifiedCompositionTo); + } else { + handleSingleSubInterfaces(unifiedCompositionTo); + } + } + + private void handleSingleSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { + UnifiedCompositionData unifiedCompositionData = unifiedCompositionTo.getUnifiedCompositionDataList().get(0); + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + List<SubInterfaceTemplateConsolidationData> subInterfaceDataList = new ArrayList<>(); + subInterfaceDataList.add(subInterfaceTemplateConsolidationData); + createSubInterfaceSubstitutionNodeTemplate(unifiedCompositionTo, subInterfaceDataList); + } + } - ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfacesByType = - UnifiedCompositionUtil.collectAllSubInterfacesOfEachTypesFromPorts( - portTemplateConsolidationDataList); + private void handleConsolidationSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { + Map<String, List<String>> portIdsPerPortType = UnifiedCompositionUtil + .collectAllPortsOfEachTypeFromComputes(unifiedCompositionTo.getUnifiedCompositionDataList()); + for (Map.Entry<String, List<String>> portIdsPerPortTypeEntry : portIdsPerPortType.entrySet()) { + List<EntityConsolidationData> portEntityConsolidationDataList = getPortConsolidationDataList(portIdsPerPortTypeEntry.getValue(), + unifiedCompositionTo.getUnifiedCompositionDataList()); + if (CollectionUtils.isEmpty(portEntityConsolidationDataList)) { + continue; + } + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = portEntityConsolidationDataList.stream() + .map(data -> (PortTemplateConsolidationData) data).collect(Collectors.toList()); + ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfacesByType = UnifiedCompositionUtil + .collectAllSubInterfacesOfEachTypesFromPorts(portTemplateConsolidationDataList); Set<String> subInterfaceTypes = subInterfacesByType.keySet(); for (String subInterfaceType : subInterfaceTypes) { - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - subInterfacesByType.get(subInterfaceType); - createSubInterfaceSubstitutionNodeTemplate(unifiedCompositionTo, - subInterfaceTemplateConsolidationDataList); - } - } - } - - private void createSubInterfaceSubstitutionNodeTemplate(UnifiedCompositionTo unifiedCompositionTo, - List<SubInterfaceTemplateConsolidationData> - subInterfaceTemplateConsolidationDataList) { - SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData = - subInterfaceTemplateConsolidationDataList.get(0); - Optional<PortTemplateConsolidationData> portTemplateConsolidationDataOptional = - subInterfaceTemplateConsolidationData.getParentPortTemplateConsolidationData(unifiedCompositionTo - .getServiceTemplate(), unifiedCompositionTo.getContext()); - if (!portTemplateConsolidationDataOptional.isPresent()) { - return; - } - PortTemplateConsolidationData portTemplateConsolidationData = portTemplateConsolidationDataOptional.get(); - String originalSubInterfaceNodeTemplateId = subInterfaceTemplateConsolidationDataList.get(0) - .getNodeTemplateId(); - NodeTemplate originalSubInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(unifiedCompositionTo - .getServiceTemplate(), originalSubInterfaceNodeTemplateId); - if (Objects.isNull(originalSubInterfaceNodeTemplate)) { - return; - } - NodeTemplate newSubInterfaceNodeTemplate = originalSubInterfaceNodeTemplate.clone(); - ComputeTemplateConsolidationData connectedComputeConsolidationData = - getConnectedComputeConsolidationData(unifiedCompositionTo.getUnifiedCompositionDataList(), - portTemplateConsolidationData.getNodeTemplateId()); - if (Objects.nonNull(connectedComputeConsolidationData)) { - NodeTemplate connectedComputeNodeTemplate = DataModelUtil.getNodeTemplate(unifiedCompositionTo - .getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(unifiedCompositionTo - .getServiceTemplate(), connectedComputeNodeTemplate.getType(), connectedComputeConsolidationData, - subInterfaceTemplateConsolidationData, unifiedCompositionTo.getContext()); - DataModelUtil.addNodeTemplate(unifiedCompositionTo.getSubstitutionServiceTemplate(), - newSubInterfaceNodeTemplateId, newSubInterfaceNodeTemplate); - List<EntityConsolidationData> entityConsolidationDataList = - new ArrayList<>(subInterfaceTemplateConsolidationDataList); - //Remove all the existing properties as we are going to create new based on the - // naming convention for the substitution - handleSubInterfaceProperties(unifiedCompositionTo, originalSubInterfaceNodeTemplateId, - newSubInterfaceNodeTemplate, entityConsolidationDataList, portTemplateConsolidationData); - //Update requirements for relationships between the consolidation entities - handleConsolidationEntitiesRequirementConnectivity(newSubInterfaceNodeTemplate, unifiedCompositionTo - .getServiceTemplate(), unifiedCompositionTo.getContext()); - removeConnectivityOut(subInterfaceTemplateConsolidationData,newSubInterfaceNodeTemplate); - } - } - - private void handleSubInterfaceProperties(UnifiedCompositionTo unifiedCompositionTo, - String subInterfaceNodeTemplateId, - NodeTemplate newSubInterfaceNodeTemplate, - List<EntityConsolidationData> - entityConsolidationDataList, - PortTemplateConsolidationData - portTemplateConsolidationData) { - UnifiedCompositionData unifiedCompositionData = unifiedCompositionTo.getUnifiedCompositionDataList().get(0); - ServiceTemplate serviceTemplate = unifiedCompositionTo.getServiceTemplate(); - TranslationContext context = unifiedCompositionTo.getContext(); - newSubInterfaceNodeTemplate.setProperties(new HashMap<>()); - for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { - String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); - Optional<List<String>> indexVarProperties = - context.getIndexVarProperties(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - nodeTemplateId); - Map<String, Object> properties = - DataModelUtil.getNodeTemplateProperties(serviceTemplate, nodeTemplateId); - if (MapUtils.isEmpty(properties)) { - continue; - } - - for (Map.Entry<String, Object> propertyEntry : properties.entrySet()) { - NodeType nodeTypeWithFlatHierarchy = - HeatToToscaUtil.getNodeTypeWithFlatHierarchy(newSubInterfaceNodeTemplate.getType(), - serviceTemplate, context); - PropertyDefinition propertyDefinition = - nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()); - String propertyType = propertyDefinition.getType(); - //Handle service_template_filter property for subinterface as we should not create inputs - // for this property - if (propertyEntry.getKey().equals(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME)) { - handleSubInterfaceServiceTemplateFilterProperty(subInterfaceNodeTemplateId, newSubInterfaceNodeTemplate, - propertyEntry.getKey(), propertyEntry.getValue(), portTemplateConsolidationData, - unifiedCompositionTo.getSubstitutionServiceTemplate()); - } else if (indexVarProperties.isPresent() - && indexVarProperties.get().contains(propertyEntry.getKey())) { - //Handle index property - handleIndexVarProperty(propertyEntry.getKey(), propertyEntry.getValue(), - newSubInterfaceNodeTemplate); - } else { - Optional<String> parameterId = - updateProperty(serviceTemplate, nodeTemplateId, newSubInterfaceNodeTemplate, - propertyEntry, UnifiedCompositionEntity.SUB_INTERFACE, unifiedCompositionData - .getComputeTemplateConsolidationData(), portTemplateConsolidationData, - unifiedCompositionTo.getUnifiedCompositionDataList(), context); - parameterId.ifPresent( - parameterIdValue -> addPropertyInputParameter(propertyType, - unifiedCompositionTo.getSubstitutionServiceTemplate(), - propertyDefinition.getEntry_schema(), parameterIdValue)); + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = subInterfacesByType.get(subInterfaceType); + createSubInterfaceSubstitutionNodeTemplate(unifiedCompositionTo, subInterfaceTemplateConsolidationDataList); + } } - } } - } - private NodeTemplate getNodeTemplate(String nodeTemplateId, ServiceTemplate serviceTemplate, - TranslationContext context) { + private void createSubInterfaceSubstitutionNodeTemplate(UnifiedCompositionTo unifiedCompositionTo, + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList) { + SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData = subInterfaceTemplateConsolidationDataList.get(0); + Optional<PortTemplateConsolidationData> portTemplateConsolidationDataOptional = subInterfaceTemplateConsolidationData + .getParentPortTemplateConsolidationData(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getContext()); + if (!portTemplateConsolidationDataOptional.isPresent()) { + return; + } + PortTemplateConsolidationData portTemplateConsolidationData = portTemplateConsolidationDataOptional.get(); + String originalSubInterfaceNodeTemplateId = subInterfaceTemplateConsolidationDataList.get(0).getNodeTemplateId(); + NodeTemplate originalSubInterfaceNodeTemplate = DataModelUtil + .getNodeTemplate(unifiedCompositionTo.getServiceTemplate(), originalSubInterfaceNodeTemplateId); + if (Objects.isNull(originalSubInterfaceNodeTemplate)) { + return; + } + NodeTemplate newSubInterfaceNodeTemplate = originalSubInterfaceNodeTemplate.clone(); + ComputeTemplateConsolidationData connectedComputeConsolidationData = getConnectedComputeConsolidationData( + unifiedCompositionTo.getUnifiedCompositionDataList(), portTemplateConsolidationData.getNodeTemplateId()); + if (Objects.nonNull(connectedComputeConsolidationData)) { + NodeTemplate connectedComputeNodeTemplate = DataModelUtil + .getNodeTemplate(unifiedCompositionTo.getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), + connectedComputeNodeTemplate.getType(), connectedComputeConsolidationData, subInterfaceTemplateConsolidationData, + unifiedCompositionTo.getContext()); + DataModelUtil + .addNodeTemplate(unifiedCompositionTo.getSubstitutionServiceTemplate(), newSubInterfaceNodeTemplateId, newSubInterfaceNodeTemplate); + List<EntityConsolidationData> entityConsolidationDataList = new ArrayList<>(subInterfaceTemplateConsolidationDataList); + //Remove all the existing properties as we are going to create new based on the + + // naming convention for the substitution + handleSubInterfaceProperties(unifiedCompositionTo, originalSubInterfaceNodeTemplateId, newSubInterfaceNodeTemplate, + entityConsolidationDataList, portTemplateConsolidationData); + //Update requirements for relationships between the consolidation entities + handleConsolidationEntitiesRequirementConnectivity(newSubInterfaceNodeTemplate, unifiedCompositionTo.getServiceTemplate(), + unifiedCompositionTo.getContext()); + removeConnectivityOut(subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplate); + } + } - NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, nodeTemplateId); + private void handleSubInterfaceProperties(UnifiedCompositionTo unifiedCompositionTo, String subInterfaceNodeTemplateId, + NodeTemplate newSubInterfaceNodeTemplate, List<EntityConsolidationData> entityConsolidationDataList, + PortTemplateConsolidationData portTemplateConsolidationData) { + UnifiedCompositionData unifiedCompositionData = unifiedCompositionTo.getUnifiedCompositionDataList().get(0); + ServiceTemplate serviceTemplate = unifiedCompositionTo.getServiceTemplate(); + TranslationContext context = unifiedCompositionTo.getContext(); + newSubInterfaceNodeTemplate.setProperties(new HashMap<>()); + for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { + String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); + Optional<List<String>> indexVarProperties = context + .getIndexVarProperties(ToscaUtil.getServiceTemplateFileName(serviceTemplate), nodeTemplateId); + Map<String, Object> properties = DataModelUtil.getNodeTemplateProperties(serviceTemplate, nodeTemplateId); + if (MapUtils.isEmpty(properties)) { + continue; + } + for (Map.Entry<String, Object> propertyEntry : properties.entrySet()) { + NodeType nodeTypeWithFlatHierarchy = HeatToToscaUtil + .getNodeTypeWithFlatHierarchy(newSubInterfaceNodeTemplate.getType(), serviceTemplate, context); + PropertyDefinition propertyDefinition = nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()); + String propertyType = propertyDefinition.getType(); + //Handle service_template_filter property for subinterface as we should not create inputs + + // for this property + if (propertyEntry.getKey().equals(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME)) { + handleSubInterfaceServiceTemplateFilterProperty(subInterfaceNodeTemplateId, newSubInterfaceNodeTemplate, propertyEntry.getKey(), + propertyEntry.getValue(), portTemplateConsolidationData, unifiedCompositionTo.getSubstitutionServiceTemplate()); + } else if (indexVarProperties.isPresent() && indexVarProperties.get().contains(propertyEntry.getKey())) { + //Handle index property + handleIndexVarProperty(propertyEntry.getKey(), propertyEntry.getValue(), newSubInterfaceNodeTemplate); + } else { + Optional<String> parameterId = updateProperty(serviceTemplate, nodeTemplateId, newSubInterfaceNodeTemplate, propertyEntry, + UnifiedCompositionEntity.SUB_INTERFACE, unifiedCompositionData.getComputeTemplateConsolidationData(), + portTemplateConsolidationData, unifiedCompositionTo.getUnifiedCompositionDataList(), context); + parameterId.ifPresent( + parameterIdValue -> addPropertyInputParameter(propertyType, unifiedCompositionTo.getSubstitutionServiceTemplate(), + propertyDefinition.getEntry_schema(), parameterIdValue)); + } + } + } + } - if (Objects.isNull(nodeTemplate)) { - nodeTemplate = context - .getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - nodeTemplateId); + private NodeTemplate getNodeTemplate(String nodeTemplateId, ServiceTemplate serviceTemplate, TranslationContext context) { + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, nodeTemplateId); + if (Objects.isNull(nodeTemplate)) { + nodeTemplate = context.getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), nodeTemplateId); + } + return nodeTemplate; + } + + private String handleCompute(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); + handleComputeNodeTemplate(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, context); + return handleComputeNodeType(serviceTemplate, substitutionServiceTemplate, computeTemplateConsolidationData); + } + + private String handleComputeNodeType(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + String computeNodeTypeId = computeNodeTemplate.getType(); + NodeType computeNodeType = DataModelUtil.getNodeType(serviceTemplate, computeNodeTypeId); + DataModelUtil.addNodeType(substitutionServiceTemplate, computeNodeTypeId, computeNodeType); + return computeNodeTypeId; + } + + private void handleComputeNodeTemplate(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); + NodeTemplate newComputeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()) + .clone(); + removeConnectivityOut(computeTemplateConsolidationData, newComputeNodeTemplate); + removeVolumeConnectivity(computeTemplateConsolidationData, newComputeNodeTemplate); + List<EntityConsolidationData> computeConsolidationDataList = getComputeConsolidationDataList(unifiedCompositionDataList); + handleProperties(serviceTemplate, newComputeNodeTemplate, substitutionServiceTemplate, COMPUTE, computeConsolidationDataList, + computeTemplateConsolidationData, unifiedCompositionDataList, context); + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + //Update requirements for relationships between the consolidation entities + handleConsolidationEntitiesRequirementConnectivity(newComputeNodeTemplate, serviceTemplate, context); + DataModelUtil.addNodeTemplate(substitutionServiceTemplate, newComputeNodeTemplateId, newComputeNodeTemplate); + //Add the node template mapping in the context for handling requirement updation + for (EntityConsolidationData data : computeConsolidationDataList) { + String newComputeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + data.getNodeTemplateId(), newComputeTemplateId); + } + } + private List<EntityConsolidationData> getComputeConsolidationDataList(List<UnifiedCompositionData> unifiedCompositionDataList) { + return unifiedCompositionDataList.stream().map(UnifiedCompositionData::getComputeTemplateConsolidationData).collect(Collectors.toList()); } - return nodeTemplate; - } + private void handleProperties(ServiceTemplate serviceTemplate, NodeTemplate nodeTemplate, ServiceTemplate substitutionServiceTemplate, + UnifiedCompositionEntity unifiedCompositionEntity, List<EntityConsolidationData> entityConsolidationDataList, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + nodeTemplate.setProperties(new HashedMap()); + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, + context, nodeTemplate); + handleNodeTemplateProperties(unifiedCompositionTo, unifiedCompositionEntity, entityConsolidationDataList, computeTemplateConsolidationData); + //Add enrich properties from openecomp node type as input to global and substitution ST + handleNodeTypeProperties(substitutionServiceTemplate, entityConsolidationDataList, nodeTemplate, unifiedCompositionEntity, + computeTemplateConsolidationData, context); + } - private String handleCompute(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); - handleComputeNodeTemplate(serviceTemplate, substitutionServiceTemplate, - unifiedCompositionDataList, context); - return handleComputeNodeType(serviceTemplate, substitutionServiceTemplate, - computeTemplateConsolidationData); - } - - private String handleComputeNodeType( - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - String computeNodeTypeId = computeNodeTemplate.getType(); - NodeType computeNodeType = - DataModelUtil.getNodeType(serviceTemplate, computeNodeTypeId); - DataModelUtil - .addNodeType(substitutionServiceTemplate, computeNodeTypeId, computeNodeType); - - return computeNodeTypeId; - } - - private void handleComputeNodeTemplate(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); - NodeTemplate newComputeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()).clone(); + private void addPortSubInterfaceIndicatorProperty(Map<String, Object> properties, EntityConsolidationData entityConsolidationData) { + properties.put(SUB_INTERFACE_INDICATOR_PROPERTY, ((PortTemplateConsolidationData) entityConsolidationData).isPortBoundToSubInterface()); + } - removeConnectivityOut(computeTemplateConsolidationData, newComputeNodeTemplate); - removeVolumeConnectivity(computeTemplateConsolidationData, newComputeNodeTemplate); + private void handleNodeTemplateProperties(UnifiedCompositionTo unifiedCompositionTo, UnifiedCompositionEntity unifiedCompositionEntity, + List<EntityConsolidationData> entityConsolidationDataList, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + List<String> propertiesWithIdenticalVal = consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity); + for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { + String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); + Optional<List<String>> indexVarProperties = unifiedCompositionTo.getContext() + .getIndexVarProperties(ToscaUtil.getServiceTemplateFileName(unifiedCompositionTo.getServiceTemplate()), nodeTemplateId); + Map<String, Object> properties = DataModelUtil.getNodeTemplateProperties(unifiedCompositionTo.getServiceTemplate(), nodeTemplateId); + if (MapUtils.isEmpty(properties)) { + continue; + } + for (Map.Entry<String, Object> propertyEntry : properties.entrySet()) { + NodeType nodeTypeWithFlatHierarchy = HeatToToscaUtil + .getNodeTypeWithFlatHierarchy(unifiedCompositionTo.getNodeTemplate().getType(), unifiedCompositionTo.getServiceTemplate(), + unifiedCompositionTo.getContext()); + PropertyDefinition propertyDefinition = nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()); + String propertyType = propertyDefinition.getType(); + if (propertiesWithIdenticalVal.contains(propertyEntry.getKey())) { + String parameterId = updateIdenticalProperty(nodeTemplateId, propertyEntry.getKey(), unifiedCompositionTo.getNodeTemplate(), + unifiedCompositionEntity, unifiedCompositionTo.getUnifiedCompositionDataList()); + addInputParameter(parameterId, propertyType, + propertyType.equals(PropertyType.LIST.getDisplayName()) ? propertyDefinition.getEntry_schema() : null, + unifiedCompositionTo.getSubstitutionServiceTemplate()); + } else if (indexVarProperties.isPresent() && indexVarProperties.get().contains(propertyEntry.getKey())) { + //Handle index property + handleIndexVarProperty(propertyEntry.getKey(), propertyEntry.getValue(), unifiedCompositionTo.getNodeTemplate()); + } else { + Optional<String> parameterId = updateProperty(unifiedCompositionTo.getServiceTemplate(), nodeTemplateId, + unifiedCompositionTo.getNodeTemplate(), propertyEntry, unifiedCompositionEntity, computeTemplateConsolidationData, + getPortTemplateConsolidationDataForPort(unifiedCompositionTo.getUnifiedCompositionDataList(), nodeTemplateId), + unifiedCompositionTo.getUnifiedCompositionDataList(), unifiedCompositionTo.getContext()); + parameterId.ifPresent( + parameterIdValue -> addPropertyInputParameter(propertyType, unifiedCompositionTo.getSubstitutionServiceTemplate(), + propertyDefinition.getEntry_schema(), parameterIdValue)); + } + } + } + } - List<EntityConsolidationData> computeConsolidationDataList = - getComputeConsolidationDataList(unifiedCompositionDataList); + private void handleIndexVarProperty(String propertyKey, Object propertyValue, NodeTemplate nodeTemplate) { + //Retain properties translated from %index% value in heat + nodeTemplate.getProperties().put(propertyKey, propertyValue); + } - handleProperties(serviceTemplate, newComputeNodeTemplate, - substitutionServiceTemplate, COMPUTE, - computeConsolidationDataList, computeTemplateConsolidationData, unifiedCompositionDataList, - context); + private void handleSubInterfaceServiceTemplateFilterProperty(String subInterfaceNodeTemplateId, NodeTemplate nodeTemplate, String propertyKey, + Object propertyValue, PortTemplateConsolidationData portTemplateConsolidationData, + ServiceTemplate substitutionServiceTemplate) { + //Retain service_template_filter (Can be present in a sub-interface resource-def) + if (propertyValue instanceof Map) { + Map<String, Object> serviceTemplateFilterPropertyMap = new HashMap<>((Map<String, Object>) propertyValue); + handleCountProperty(subInterfaceNodeTemplateId, nodeTemplate, portTemplateConsolidationData, substitutionServiceTemplate, + serviceTemplateFilterPropertyMap); + DataModelUtil.addNodeTemplateProperty(nodeTemplate, propertyKey, serviceTemplateFilterPropertyMap); + } + } - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - //Update requirements for relationships between the consolidation entities - handleConsolidationEntitiesRequirementConnectivity( - newComputeNodeTemplate, - serviceTemplate, context); - DataModelUtil - .addNodeTemplate(substitutionServiceTemplate, - newComputeNodeTemplateId, newComputeNodeTemplate); - //Add the node template mapping in the context for handling requirement updation - for (EntityConsolidationData data : computeConsolidationDataList) { - String newComputeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), data.getNodeTemplateId(), - newComputeTemplateId); - } - } - - private List<EntityConsolidationData> getComputeConsolidationDataList( - List<UnifiedCompositionData> unifiedCompositionDataList) { - return unifiedCompositionDataList.stream() - .map(UnifiedCompositionData::getComputeTemplateConsolidationData) - .collect(Collectors.toList()); - } - - - private void handleProperties(ServiceTemplate serviceTemplate, - NodeTemplate nodeTemplate, - ServiceTemplate substitutionServiceTemplate, - UnifiedCompositionEntity unifiedCompositionEntity, - List<EntityConsolidationData> entityConsolidationDataList, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - nodeTemplate.setProperties(new HashedMap()); - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, substitutionServiceTemplate,unifiedCompositionDataList, context, nodeTemplate); - handleNodeTemplateProperties(unifiedCompositionTo, unifiedCompositionEntity, entityConsolidationDataList, computeTemplateConsolidationData); - //Add enrich properties from openecomp node type as input to global and substitution ST - handleNodeTypeProperties(substitutionServiceTemplate, - entityConsolidationDataList, nodeTemplate, unifiedCompositionEntity, - computeTemplateConsolidationData, context); - } - - private void addPortSubInterfaceIndicatorProperty(Map<String, Object> properties, - EntityConsolidationData entityConsolidationData) { - properties.put(SUB_INTERFACE_INDICATOR_PROPERTY, - ((PortTemplateConsolidationData) entityConsolidationData).isPortBoundToSubInterface()); - } - - private void handleNodeTemplateProperties(UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionEntity unifiedCompositionEntity, - List<EntityConsolidationData> - entityConsolidationDataList, - ComputeTemplateConsolidationData - computeTemplateConsolidationData - ) { - List<String> propertiesWithIdenticalVal = - consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity); - - for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { - String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); - Optional<List<String>> indexVarProperties = - unifiedCompositionTo.getContext().getIndexVarProperties(ToscaUtil.getServiceTemplateFileName(unifiedCompositionTo.getServiceTemplate()), - nodeTemplateId); - Map<String, Object> properties = - DataModelUtil.getNodeTemplateProperties(unifiedCompositionTo.getServiceTemplate(), - nodeTemplateId); - if (MapUtils.isEmpty(properties)) { - continue; - } - - for (Map.Entry<String, Object> propertyEntry : properties.entrySet()) { - NodeType nodeTypeWithFlatHierarchy = - HeatToToscaUtil.getNodeTypeWithFlatHierarchy(unifiedCompositionTo.getNodeTemplate().getType(), - unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getContext()); - PropertyDefinition propertyDefinition = - nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()); - String propertyType = propertyDefinition.getType(); - - if (propertiesWithIdenticalVal.contains(propertyEntry.getKey())) { - String parameterId = - updateIdenticalProperty(nodeTemplateId, propertyEntry.getKey(), - unifiedCompositionTo.getNodeTemplate(),unifiedCompositionEntity, unifiedCompositionTo.getUnifiedCompositionDataList()); - - addInputParameter( - parameterId, propertyType, - propertyType.equals(PropertyType.LIST.getDisplayName()) ? propertyDefinition - .getEntry_schema() : null, - unifiedCompositionTo.getSubstitutionServiceTemplate()); - } else if (indexVarProperties.isPresent() - && indexVarProperties.get().contains(propertyEntry.getKey())) { - //Handle index property - handleIndexVarProperty(propertyEntry.getKey(), propertyEntry.getValue(), - unifiedCompositionTo.getNodeTemplate()); - } else { - Optional<String> parameterId = - updateProperty(unifiedCompositionTo.getServiceTemplate(), nodeTemplateId, unifiedCompositionTo.getNodeTemplate(), propertyEntry, - unifiedCompositionEntity, computeTemplateConsolidationData, - getPortTemplateConsolidationDataForPort(unifiedCompositionTo.getUnifiedCompositionDataList(), nodeTemplateId), - unifiedCompositionTo.getUnifiedCompositionDataList(), - unifiedCompositionTo.getContext()); - parameterId.ifPresent( - parameterIdValue -> addPropertyInputParameter(propertyType, - unifiedCompositionTo.getSubstitutionServiceTemplate(), - propertyDefinition.getEntry_schema(), parameterIdValue)); - } - } - } - } - - private void handleIndexVarProperty(String propertyKey, Object propertyValue, - NodeTemplate nodeTemplate) { - //Retain properties translated from %index% value in heat - nodeTemplate.getProperties().put(propertyKey, propertyValue); - } - - private void handleSubInterfaceServiceTemplateFilterProperty(String subInterfaceNodeTemplateId, - NodeTemplate nodeTemplate, - String propertyKey, - Object propertyValue, - PortTemplateConsolidationData - portTemplateConsolidationData, - ServiceTemplate substitutionServiceTemplate) { - //Retain service_template_filter (Can be present in a sub-interface resource-def) - if (propertyValue instanceof Map) { - Map<String, Object> serviceTemplateFilterPropertyMap = new HashMap<>((Map<String, Object>) propertyValue); - handleCountProperty(subInterfaceNodeTemplateId, nodeTemplate, portTemplateConsolidationData, - substitutionServiceTemplate, serviceTemplateFilterPropertyMap); - DataModelUtil.addNodeTemplateProperty(nodeTemplate, propertyKey, serviceTemplateFilterPropertyMap); - } - } - - private void handleCountProperty(String subInterfaceNodeTemplateId, NodeTemplate nodeTemplate, - PortTemplateConsolidationData portTemplateConsolidationData, - ServiceTemplate substitutionServiceTemplate, - Map<String, Object> serviceTemplatePropertyMap) { - String countInputParameterId = getSubInterfaceInputParameterId(nodeTemplate.getType(), subInterfaceNodeTemplateId, + private void handleCountProperty(String subInterfaceNodeTemplateId, NodeTemplate nodeTemplate, + PortTemplateConsolidationData portTemplateConsolidationData, ServiceTemplate substitutionServiceTemplate, + Map<String, Object> serviceTemplatePropertyMap) { + String countInputParameterId = getSubInterfaceInputParameterId(nodeTemplate.getType(), subInterfaceNodeTemplateId, ToscaConstants.SERVICE_TEMPLATE_FILTER_COUNT, portTemplateConsolidationData); - EntrySchema entrySchema = new EntrySchema(); - entrySchema.setType(PropertyType.FLOAT.getDisplayName()); - addInputParameter(countInputParameterId, PropertyType.LIST.getDisplayName(), entrySchema, - substitutionServiceTemplate); - Map<String, List<String>> countPropertyValueInputParam = getPropertyValueInputParam(countInputParameterId); - serviceTemplatePropertyMap.remove(ToscaConstants.COUNT_PROPERTY_NAME); - serviceTemplatePropertyMap.put(ToscaConstants.COUNT_PROPERTY_NAME, countPropertyValueInputParam); - } - - private void handleNodeTypeProperties(ServiceTemplate substitutionServiceTemplate, - List<EntityConsolidationData> entityConsolidationDataList, - NodeTemplate nodeTemplate, - UnifiedCompositionEntity compositionEntity, - ComputeTemplateConsolidationData - computeTemplateConsolidationData, - TranslationContext context) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - Optional<NodeType> enrichNodeType; - List<String> enrichProperties; - - if (compositionEntity.equals(UnifiedCompositionEntity.PORT)) { - enrichNodeType = - toscaAnalyzerService.fetchNodeType(ToscaNodeType.NETWORK_PORT, - context.getGlobalServiceTemplates().values()); - enrichProperties = TranslationContext.getEnrichPortResourceProperties(); - if (!enrichNodeType.isPresent() || Objects.isNull(enrichProperties)) { - return; - } - } else { - return; - } - - Map<String, Object> nodeTemplateProperties = nodeTemplate.getProperties(); - Map<String, PropertyDefinition> enrichNodeTypeProperties = enrichNodeType.get().getProperties(); - if (Objects.nonNull(enrichNodeTypeProperties)) { - for (String enrichPropertyName : enrichProperties) { - handleEntityConsolidationDataNodeTypeProperties( - enrichPropertyName, substitutionServiceTemplate, - enrichNodeType.get(), nodeTemplate, compositionEntity, computeTemplateConsolidationData, - entityConsolidationDataList, nodeTemplateProperties, context); - } - } - } - - private void handleEntityConsolidationDataNodeTypeProperties(String enrichPropertyName, - ServiceTemplate substitutionServiceTemplate, - NodeType enrichNodeType, - NodeTemplate nodeTemplate, - UnifiedCompositionEntity compositionEntity, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - List<EntityConsolidationData> entityConsolidationDataList, - Map<String, Object> nodeTemplateProperties, - TranslationContext context) { - - String propertyType; - - for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { - String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); - - String inputParamId = - getParameterId(nodeTemplateId, nodeTemplate, enrichPropertyName, - compositionEntity, computeTemplateConsolidationData, - (PortTemplateConsolidationData) entityConsolidationData); - Map<String, String> propertyValMap = new HashMap<>(); - - context - .addNewPropertyIdToNodeTemplate( - ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate), - inputParamId, nodeTemplateProperties.get(enrichPropertyName)); - - if (nodeTemplateProperties.containsKey(enrichPropertyName)) { - handleExistingEnrichedProperty(enrichPropertyName, nodeTemplateProperties, inputParamId); - } else { - propertyValMap.put(GET_INPUT.getFunctionName(), inputParamId); - nodeTemplate.getProperties().put(enrichPropertyName, propertyValMap); - } - propertyType = - enrichNodeType.getProperties().get(enrichPropertyName).getType(); - - addPropertyInputParameter(propertyType, substitutionServiceTemplate, enrichNodeType - .getProperties().get(enrichPropertyName).getEntry_schema(), - inputParamId); - - } - } - - private void handleExistingEnrichedProperty(String enrichPropertyName, - Map<String, Object> nodeTemplateProperties, - String inputParamId) { - Object enrichedProperty = nodeTemplateProperties.get(enrichPropertyName); - if (!isPropertyContainsToscaFunction(enrichedProperty)) { - Map<String, Object> propertyWithGetInput = new HashMap<>(); - propertyWithGetInput.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); - nodeTemplateProperties.put(enrichPropertyName, propertyWithGetInput); - } - } - - - private boolean isPropertyContainsToscaFunction(Object propertyValue) { - ToscaFunctions[] values = ToscaFunctions.values(); - for (ToscaFunctions toscaFunction : values) { - if (isIncludeToscaFunc(propertyValue, toscaFunction)) { - return true; - } - } - - return false; - } - - - private void addPropertyInputParameter(String propertyType, - ServiceTemplate substitutionServiceTemplate, - EntrySchema entrySchema, String parameterId) { - if (Objects.isNull(propertyType)) { - return; - } - if (isParameterBelongsToEnrichedPortProperties(parameterId)) { - addInputParameter(parameterId, - propertyType, - propertyType.equals(PropertyType.LIST.getDisplayName()) ? entrySchema : null, - substitutionServiceTemplate); - } else if (isPropertySimpleType(propertyType)) { - addInputParameter(parameterId, PropertyType.LIST.getDisplayName(), - DataModelUtil.createEntrySchema(propertyType.toLowerCase(), null, null), - substitutionServiceTemplate); - - } else if (propertyType.equals(PropertyTypeExt.JSON.getDisplayName()) || - (Objects.nonNull(entrySchema) && isPropertySimpleType(entrySchema.getType()))) { - addInputParameter(parameterId, PropertyType.LIST.getDisplayName(), - DataModelUtil.createEntrySchema(PropertyTypeExt.JSON.getDisplayName(), null, null), - substitutionServiceTemplate); - } else { - addInputParameter(parameterId, analyzeParameterType(propertyType), DataModelUtil - .createEntrySchema(analyzeEntrySchemaType(propertyType, entrySchema), null, null), - substitutionServiceTemplate); - } - } - - private boolean isParameterBelongsToEnrichedPortProperties(String parameterId) { - List enrichPortResourceProperties = TranslationContext.getEnrichPortResourceProperties(); - - for (int i = 0; i < enrichPortResourceProperties.size(); i++) { - if (parameterId.contains((CharSequence) enrichPortResourceProperties.get(i))) { - return true; - } - } - - return false; - } - - private boolean isPropertySimpleType(String propertyType) { - return !Objects.isNull(propertyType) - && (PropertyType.getSimplePropertyTypes().contains(propertyType.toLowerCase())); - } - - private String analyzeParameterType(String propertyType) { - return propertyType.equalsIgnoreCase(PropertyType.LIST.getDisplayName()) ? PropertyType.LIST - .getDisplayName() : propertyType; - } - - private String analyzeEntrySchemaType(String propertyType, EntrySchema entrySchema) { - return propertyType.equalsIgnoreCase(PropertyType.LIST.getDisplayName()) && entrySchema != null ? - entrySchema.getType() : null; - } - - private void handleConsolidationEntitiesRequirementConnectivity(NodeTemplate nodeTemplate, - ServiceTemplate serviceTemplate, - TranslationContext context) { - List<Map<String, RequirementAssignment>> nodeTemplateRequirements = DataModelUtil - .getNodeTemplateRequirementList(nodeTemplate); - if (CollectionUtils.isEmpty(nodeTemplateRequirements)) { - return; - } - - for (Map<String, RequirementAssignment> requirement : nodeTemplateRequirements) { - for (Map.Entry<String, RequirementAssignment> entry : requirement.entrySet()) { - RequirementAssignment requirementAssignment = entry.getValue(); - String requirementNode = requirementAssignment.getNode(); - String unifiedNodeTemplateId = - context.getUnifiedSubstitutionNodeTemplateId(serviceTemplate, - requirementNode); - if (unifiedNodeTemplateId != null) { - //Update the node id in the requirement - requirementAssignment.setNode(unifiedNodeTemplateId); - } - } - } - nodeTemplate.setRequirements(nodeTemplateRequirements); - } - - /** - * Update the node references in the volume relationship templates. - * - * @param serviceTemplate the service template - * @param context the context - */ - private void updateVolumeRelationshipTemplate(ServiceTemplate serviceTemplate, - String relationshipId, - TranslationContext context) { - Map<String, RelationshipTemplate> relationshipTemplates = DataModelUtil - .getRelationshipTemplates(serviceTemplate); - if (relationshipTemplates != null) { - RelationshipTemplate relationshipTemplate = relationshipTemplates.get(relationshipId); - if (relationshipTemplate != null) { - String relationshipTemplateType = relationshipTemplate.getType(); - if (relationshipTemplateType.equals(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO)) { - handleCinderVolumeAttachmentRelationshipTemplate(serviceTemplate, - relationshipTemplate, context); - } - } - } - } - - - private void handleCinderVolumeAttachmentRelationshipTemplate(ServiceTemplate - substitutionServiceTemplate, - RelationshipTemplate - relationshipTemplate, - TranslationContext context) { - Map<String, Object> properties = relationshipTemplate.getProperties(); - properties.computeIfPresent(HeatConstants.INSTANCE_UUID_PROPERTY_NAME, (key, value) -> - context.getUnifiedAbstractNodeTemplateId(substitutionServiceTemplate, - (String) value)); - } - - private String updateIdenticalProperty(String nodeTemplateId, String propertyId, - NodeTemplate nodeTemplate, - UnifiedCompositionEntity unifiedCompositionEntity, - List<UnifiedCompositionData> unifiedCompositionDataList) { - - String inputParamId = null; - Map<String, Object> propertyVal = new HashMap<>(); - - switch (unifiedCompositionEntity) { - case COMPUTE: - inputParamId = COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX + propertyId - + COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX; - propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); - nodeTemplate.getProperties().put(propertyId, propertyVal); - break; - case PORT: - PortTemplateConsolidationData portTemplateConsolidationData = - getPortTemplateConsolidationDataForPort(unifiedCompositionDataList, - nodeTemplateId); - String portType = null; - if (Objects.nonNull(portTemplateConsolidationData)) { - portType = portTemplateConsolidationData.getPortType(); - } - ComputeTemplateConsolidationData computeTemplateConsolidationData = - getConnectedComputeConsolidationData(unifiedCompositionDataList, nodeTemplateId); - inputParamId = getInputParamIdForPort(nodeTemplateId, propertyId, portType, computeTemplateConsolidationData); - propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); - nodeTemplate.getProperties().put(propertyId, propertyVal); - break; - default: - break; - } - return inputParamId; - } - - private String getInputParamIdForPort(String nodeTemplateId, String propertyId, String portType, - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - String inputParamId; - if (Objects.isNull(computeTemplateConsolidationData) - || computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { - inputParamId = - UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + nodeTemplateId + "_" + - propertyId; - - } else { - inputParamId = - UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + portType + "_" - + propertyId; - } - return inputParamId; - } - - private void addInputParameter(String parameterId, - String parameterType, - EntrySchema entrySchema, - ServiceTemplate serviceTemplate) { - - ParameterDefinition parameterDefinition = DataModelUtil.createParameterDefinition(parameterType, null, true, - null, entrySchema, null); - - - DataModelUtil - .addInputParameterToTopologyTemplate(serviceTemplate, parameterId, parameterDefinition); - } - - // Return the input parameter Id which is used in the new property value if there is one - private Optional<String> updateProperty( - ServiceTemplate serviceTemplate, - String nodeTemplateId, NodeTemplate nodeTemplate, - Map.Entry<String, Object> propertyEntry, - UnifiedCompositionEntity compositionEntity, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - PortTemplateConsolidationData portTemplateConsolidationData, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - - if (handleGetAttrFromConsolidationNodes(serviceTemplate, nodeTemplateId, nodeTemplate, - propertyEntry, unifiedCompositionDataList, context)) { - return Optional.empty(); - } - - - String inputParamId = - getParameterId(nodeTemplateId, nodeTemplate, propertyEntry.getKey(), compositionEntity, - computeTemplateConsolidationData, portTemplateConsolidationData); - Map<String, List<String>> propertyVal = getPropertyValueInputParam(inputParamId); - nodeTemplate.getProperties().put(propertyEntry.getKey(), propertyVal); - return Optional.of(inputParamId); - } - - private Map<String, List<String>> getPropertyValueInputParam(String inputParamId) { - Map<String, List<String>> propertyVal = new HashMap<>(); - List<String> getInputFuncParams = new ArrayList<>(); - getInputFuncParams.add(inputParamId); - getInputFuncParams.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); - propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), getInputFuncParams); - return propertyVal; - } - - private boolean handleGetAttrFromConsolidationNodes( - ServiceTemplate serviceTemplate, - String nodeTemplateId, NodeTemplate nodeTemplate, - Map.Entry<String, Object> propertyEntry, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType = - getAllConsolidationNodeTemplateIdAndType(unifiedCompositionDataList); - - Set<String> consolidationNodeTemplateIds = consolidationNodeTemplateIdAndType.keySet(); - Map<String, String> entityIdToType = ConsolidationService.getConsolidationEntityIdToType( - serviceTemplate, context.getConsolidationData()); - boolean includeGetAttrFromConsolidationNodes = false; - boolean includeGetAttrFromOutsideNodes = false; - boolean isGetAttrFromConsolidationIsFromSameType = false; - List<List<Object>> getAttrFunctionList = extractGetAttrFunction(propertyEntry.getValue()); - for (List<Object> getAttrFunc : getAttrFunctionList) { - String getAttrNodeId = (String) getAttrFunc.get(0); - if (consolidationNodeTemplateIds.contains(getAttrNodeId)) { - includeGetAttrFromConsolidationNodes = true; - if (isGetAttrNodeTemplateFromSameType(nodeTemplateId, getAttrNodeId, entityIdToType)) { - isGetAttrFromConsolidationIsFromSameType = true; - } - } else { - includeGetAttrFromOutsideNodes = true; - } - } - if ((includeGetAttrFromConsolidationNodes && includeGetAttrFromOutsideNodes) - || - (includeGetAttrFromConsolidationNodes && isIncludeToscaFunc(propertyEntry.getValue(), - ToscaFunctions.GET_INPUT))) { - //This case is currently not supported - this property will be ignored - return true; - } else if (includeGetAttrFromConsolidationNodes && !isGetAttrFromConsolidationIsFromSameType) { - Object clonedPropertyValue = getClonedPropertyValue(propertyEntry); - List<List<Object>> clonedGetAttrFuncList = extractGetAttrFunction(clonedPropertyValue); - for (List<Object> getAttrFunc : clonedGetAttrFuncList) { - String targetNodeTemplateId = (String) getAttrFunc.get(0); - if (consolidationNodeTemplateIds.contains(targetNodeTemplateId)) { - updatePropertyGetAttrFunc(serviceTemplate, unifiedCompositionDataList, - consolidationNodeTemplateIdAndType, targetNodeTemplateId, getAttrFunc, context); - } - } - nodeTemplate.getProperties().put(propertyEntry.getKey(), clonedPropertyValue); - return true; - } - return false; - } - - private boolean isGetAttrNodeTemplateFromSameType(String sourceNodeTemplateId, - String targetNodeTemplateId, - Map<String, String> nodeTemplateIdToType) { - - if (Objects.isNull(nodeTemplateIdToType.get(sourceNodeTemplateId)) - || Objects.isNull(nodeTemplateIdToType.get(targetNodeTemplateId))) { - return false; - } - - return nodeTemplateIdToType.get(sourceNodeTemplateId).equals(nodeTemplateIdToType - .get(targetNodeTemplateId)); - } - - private void updatePropertyGetAttrFunc( - ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType, - String targetNodeTemplateId, - List<Object> getAttrFunc, TranslationContext context) { - UnifiedCompositionEntity targetCompositionEntity = - consolidationNodeTemplateIdAndType.get(targetNodeTemplateId); - String targetNewNodeTemplateId = - getNewNodeTemplateId(serviceTemplate, unifiedCompositionDataList, targetNodeTemplateId, - targetCompositionEntity, context); - getAttrFunc.set(0, targetNewNodeTemplateId); - } - - private String getNewNodeTemplateId(ServiceTemplate serviceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - String nodeTemplateId, - UnifiedCompositionEntity compositionEntity, - TranslationContext context) { - String newNodeTemplateId = nodeTemplateId; - String nodeTemplateIdGeneratorImpl = unifiedSubstitutionNodeTemplateIdGeneratorImplMap.get(compositionEntity); - UnifiedSubstitutionNodeTemplateIdGenerator nodeTemplateIdGenerator = - CommonMethods.newInstance(nodeTemplateIdGeneratorImpl, UnifiedSubstitutionNodeTemplateIdGenerator.class); - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, null, - unifiedCompositionDataList, context, null); - Optional<String> generatedNodeTemplateId = nodeTemplateIdGenerator.generate(unifiedCompositionTo, nodeTemplateId); - if (generatedNodeTemplateId.isPresent()) { - newNodeTemplateId = generatedNodeTemplateId.get(); - } - return newNodeTemplateId; - } - - private String getNewNodeTemplateId(String origNodeTemplateId, - String serviceTemplateFileName, - ServiceTemplate serviceTemplate, - TranslationContext context) { - ConsolidationData consolidationData = context.getConsolidationData(); - - if (isIdIsOfExpectedType(origNodeTemplateId, UnifiedCompositionEntity.PORT, - serviceTemplateFileName, - context)) { - return handleIdOfPort(origNodeTemplateId, serviceTemplateFileName, consolidationData); - } else if (isIdIsOfExpectedType(origNodeTemplateId, COMPUTE, - serviceTemplateFileName, context)) { - NodeTemplate nodeTemplate = - getComputeNodeTemplate(origNodeTemplateId, serviceTemplate, context); - return getComputeTypeSuffix(nodeTemplate.getType()); - } - - return null; - } - - private Object getClonedPropertyValue(Map.Entry<String, Object> propertyEntry) { - if (propertyEntry.getValue() instanceof Map) { - return getClonedObject(propertyEntry.getValue(), Map.class); - } else if (propertyEntry.getValue() instanceof List) { - return getClonedObject(propertyEntry.getValue(), List.class); - } - return propertyEntry.getValue(); - } - - - private String getParameterId(String nodeTemplateId, NodeTemplate nodeTemplate, String propertyId, - UnifiedCompositionEntity unifiedCompositionEntity, - ComputeTemplateConsolidationData - computeTemplateConsolidationData, - PortTemplateConsolidationData portTemplateConsolidationData) { - String paramterId = propertyId; - switch (unifiedCompositionEntity) { - case COMPUTE: - paramterId = COMPUTE.getDisplayName().toLowerCase() + "_" - + getComputeTypeSuffix(nodeTemplate.getType()) + "_" + propertyId; - break; - case PORT: - String portType = portTemplateConsolidationData.getPortType(); - if (Objects.isNull(computeTemplateConsolidationData) - || (computeTemplateConsolidationData.getPorts().get(portType) != null - && computeTemplateConsolidationData.getPorts().get(portType).size() > 1)) { - paramterId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" - + nodeTemplateId + "_" + propertyId; + EntrySchema entrySchema = new EntrySchema(); + entrySchema.setType(PropertyType.FLOAT.getDisplayName()); + addInputParameter(countInputParameterId, PropertyType.LIST.getDisplayName(), entrySchema, substitutionServiceTemplate); + Map<String, List<String>> countPropertyValueInputParam = getPropertyValueInputParam(countInputParameterId); + serviceTemplatePropertyMap.remove(ToscaConstants.COUNT_PROPERTY_NAME); + serviceTemplatePropertyMap.put(ToscaConstants.COUNT_PROPERTY_NAME, countPropertyValueInputParam); + } + + private void handleNodeTypeProperties(ServiceTemplate substitutionServiceTemplate, List<EntityConsolidationData> entityConsolidationDataList, + NodeTemplate nodeTemplate, UnifiedCompositionEntity compositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, TranslationContext context) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + Optional<NodeType> enrichNodeType; + List<String> enrichProperties; + if (compositionEntity.equals(UnifiedCompositionEntity.PORT)) { + enrichNodeType = toscaAnalyzerService.fetchNodeType(ToscaNodeType.NETWORK_PORT, context.getGlobalServiceTemplates().values()); + enrichProperties = TranslationContext.getEnrichPortResourceProperties(); + if (!enrichNodeType.isPresent() || Objects.isNull(enrichProperties)) { + return; + } } else { - paramterId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + portType + "_" - + propertyId; - } - break; - case SUB_INTERFACE: - paramterId = getSubInterfaceInputParameterId(nodeTemplate.getType(), nodeTemplateId, propertyId, - portTemplateConsolidationData); - break; - default: - break; - } - return paramterId; - } - - private String getSubInterfaceInputParameterId(String type, - String nodeTemplateId, - String propertyId, - PortTemplateConsolidationData portTemplateConsolidationData) { - String subInterfaceType = getSubInterfaceTypeSuffix(type); - if (Objects.isNull(portTemplateConsolidationData) - || portTemplateConsolidationData.isSubInterfaceNodeTemplateIdParameter(type)) { - return UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_" - + nodeTemplateId + "_" + propertyId; - } - return UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_" - + subInterfaceType + "_" + propertyId; - } - - private void removeConnectivityOut(EntityConsolidationData entityConsolidationData, - NodeTemplate nodeTemplate) { + return; + } + Map<String, Object> nodeTemplateProperties = nodeTemplate.getProperties(); + Map<String, PropertyDefinition> enrichNodeTypeProperties = enrichNodeType.get().getProperties(); + if (Objects.nonNull(enrichNodeTypeProperties)) { + for (String enrichPropertyName : enrichProperties) { + handleEntityConsolidationDataNodeTypeProperties(enrichPropertyName, substitutionServiceTemplate, enrichNodeType.get(), nodeTemplate, + compositionEntity, computeTemplateConsolidationData, entityConsolidationDataList, nodeTemplateProperties, context); + } + } + } - Multimap<String, RequirementAssignmentData> nodesConnectedOut = entityConsolidationData.getNodesConnectedOut(); + private void handleEntityConsolidationDataNodeTypeProperties(String enrichPropertyName, ServiceTemplate substitutionServiceTemplate, + NodeType enrichNodeType, NodeTemplate nodeTemplate, + UnifiedCompositionEntity compositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + List<EntityConsolidationData> entityConsolidationDataList, + Map<String, Object> nodeTemplateProperties, TranslationContext context) { + String propertyType; + for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { + String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); + String inputParamId = getParameterId(nodeTemplateId, nodeTemplate, enrichPropertyName, compositionEntity, + computeTemplateConsolidationData, (PortTemplateConsolidationData) entityConsolidationData); + Map<String, String> propertyValMap = new HashMap<>(); + context.addNewPropertyIdToNodeTemplate(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate), inputParamId, + nodeTemplateProperties.get(enrichPropertyName)); + if (nodeTemplateProperties.containsKey(enrichPropertyName)) { + handleExistingEnrichedProperty(enrichPropertyName, nodeTemplateProperties, inputParamId); + } else { + propertyValMap.put(GET_INPUT.getFunctionName(), inputParamId); + nodeTemplate.getProperties().put(enrichPropertyName, propertyValMap); + } + propertyType = enrichNodeType.getProperties().get(enrichPropertyName).getType(); + addPropertyInputParameter(propertyType, substitutionServiceTemplate, + enrichNodeType.getProperties().get(enrichPropertyName).getEntry_schema(), inputParamId); + } + } - if (CommonUtil.isMultimapEmpty(nodesConnectedOut)) { + private void handleExistingEnrichedProperty(String enrichPropertyName, Map<String, Object> nodeTemplateProperties, String inputParamId) { + Object enrichedProperty = nodeTemplateProperties.get(enrichPropertyName); + if (!isPropertyContainsToscaFunction(enrichedProperty)) { + Map<String, Object> propertyWithGetInput = new HashMap<>(); + propertyWithGetInput.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); + nodeTemplateProperties.put(enrichPropertyName, propertyWithGetInput); + } + } + + private boolean isPropertyContainsToscaFunction(Object propertyValue) { + ToscaFunctions[] values = ToscaFunctions.values(); + for (ToscaFunctions toscaFunction : values) { + if (isIncludeToscaFunc(propertyValue, toscaFunction)) { + return true; + } + } + return false; + } + + private void addPropertyInputParameter(String propertyType, ServiceTemplate substitutionServiceTemplate, EntrySchema entrySchema, + String parameterId) { + if (Objects.isNull(propertyType)) { return; } + if (isParameterBelongsToEnrichedPortProperties(parameterId)) { + addInputParameter(parameterId, propertyType, propertyType.equals(PropertyType.LIST.getDisplayName()) ? entrySchema : null, + substitutionServiceTemplate); + } else if (isPropertySimpleType(propertyType)) { + addInputParameter(parameterId, PropertyType.LIST.getDisplayName(), + DataModelUtil.createEntrySchema(propertyType.toLowerCase(), null, null), substitutionServiceTemplate); + } else if (propertyType.equals(PropertyTypeExt.JSON.getDisplayName()) || (Objects.nonNull(entrySchema) && isPropertySimpleType( + entrySchema.getType()))) { + addInputParameter(parameterId, PropertyType.LIST.getDisplayName(), + DataModelUtil.createEntrySchema(PropertyTypeExt.JSON.getDisplayName(), null, null), substitutionServiceTemplate); + } else { + addInputParameter(parameterId, analyzeParameterType(propertyType), + DataModelUtil.createEntrySchema(analyzeEntrySchemaType(propertyType, entrySchema), null, null), substitutionServiceTemplate); + } + } - nodesConnectedOut.values().forEach(requirementAssignmentData -> - DataModelUtil.removeRequirementsAssignment(nodeTemplate.getRequirements(), - requirementAssignmentData.getRequirementId()) - ); + private boolean isParameterBelongsToEnrichedPortProperties(String parameterId) { + List enrichPortResourceProperties = TranslationContext.getEnrichPortResourceProperties(); + for (int i = 0; i < enrichPortResourceProperties.size(); i++) { + if (parameterId.contains((CharSequence) enrichPortResourceProperties.get(i))) { + return true; + } + } + return false; + } + + private boolean isPropertySimpleType(String propertyType) { + return !Objects.isNull(propertyType) && (PropertyType.getSimplePropertyTypes().contains(propertyType.toLowerCase())); + } + + private String analyzeParameterType(String propertyType) { + return propertyType.equalsIgnoreCase(PropertyType.LIST.getDisplayName()) ? PropertyType.LIST.getDisplayName() : propertyType; + } + + private String analyzeEntrySchemaType(String propertyType, EntrySchema entrySchema) { + return propertyType.equalsIgnoreCase(PropertyType.LIST.getDisplayName()) && entrySchema != null ? entrySchema.getType() : null; + } + + private void handleConsolidationEntitiesRequirementConnectivity(NodeTemplate nodeTemplate, ServiceTemplate serviceTemplate, + TranslationContext context) { + List<Map<String, RequirementAssignment>> nodeTemplateRequirements = DataModelUtil.getNodeTemplateRequirementList(nodeTemplate); + if (CollectionUtils.isEmpty(nodeTemplateRequirements)) { + return; + } + for (Map<String, RequirementAssignment> requirement : nodeTemplateRequirements) { + for (Map.Entry<String, RequirementAssignment> entry : requirement.entrySet()) { + RequirementAssignment requirementAssignment = entry.getValue(); + String requirementNode = requirementAssignment.getNode(); + String unifiedNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId(serviceTemplate, requirementNode); + if (unifiedNodeTemplateId != null) { + //Update the node id in the requirement + requirementAssignment.setNode(unifiedNodeTemplateId); + } + } + } + nodeTemplate.setRequirements(nodeTemplateRequirements); + } + + /** + * Update the node references in the volume relationship templates. + * + * @param serviceTemplate the service template + * @param context the context + */ + private void updateVolumeRelationshipTemplate(ServiceTemplate serviceTemplate, String relationshipId, TranslationContext context) { + Map<String, RelationshipTemplate> relationshipTemplates = DataModelUtil.getRelationshipTemplates(serviceTemplate); + if (relationshipTemplates != null) { + RelationshipTemplate relationshipTemplate = relationshipTemplates.get(relationshipId); + if (relationshipTemplate != null) { + String relationshipTemplateType = relationshipTemplate.getType(); + if (relationshipTemplateType.equals(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO)) { + handleCinderVolumeAttachmentRelationshipTemplate(serviceTemplate, relationshipTemplate, context); + } + } + } + } + + private void handleCinderVolumeAttachmentRelationshipTemplate(ServiceTemplate substitutionServiceTemplate, + RelationshipTemplate relationshipTemplate, TranslationContext context) { + Map<String, Object> properties = relationshipTemplate.getProperties(); + properties.computeIfPresent(HeatConstants.INSTANCE_UUID_PROPERTY_NAME, + (key, value) -> context.getUnifiedAbstractNodeTemplateId(substitutionServiceTemplate, (String) value)); + } + + private String updateIdenticalProperty(String nodeTemplateId, String propertyId, NodeTemplate nodeTemplate, + UnifiedCompositionEntity unifiedCompositionEntity, + List<UnifiedCompositionData> unifiedCompositionDataList) { + String inputParamId = null; + Map<String, Object> propertyVal = new HashMap<>(); + switch (unifiedCompositionEntity) { + case COMPUTE: + inputParamId = COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX + propertyId + COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX; + propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); + nodeTemplate.getProperties().put(propertyId, propertyVal); + break; + case PORT: + PortTemplateConsolidationData portTemplateConsolidationData = getPortTemplateConsolidationDataForPort(unifiedCompositionDataList, + nodeTemplateId); + String portType = null; + if (Objects.nonNull(portTemplateConsolidationData)) { + portType = portTemplateConsolidationData.getPortType(); + } + ComputeTemplateConsolidationData computeTemplateConsolidationData = getConnectedComputeConsolidationData(unifiedCompositionDataList, + nodeTemplateId); + inputParamId = getInputParamIdForPort(nodeTemplateId, propertyId, portType, computeTemplateConsolidationData); + propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); + nodeTemplate.getProperties().put(propertyId, propertyVal); + break; + default: + break; + } + return inputParamId; + } + + private String getInputParamIdForPort(String nodeTemplateId, String propertyId, String portType, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + String inputParamId; + if (Objects.isNull(computeTemplateConsolidationData) || computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { + inputParamId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + nodeTemplateId + "_" + propertyId; + } else { + inputParamId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + portType + "_" + propertyId; + } + return inputParamId; + } + + private void addInputParameter(String parameterId, String parameterType, EntrySchema entrySchema, ServiceTemplate serviceTemplate) { + ParameterDefinition parameterDefinition = DataModelUtil.createParameterDefinition(parameterType, null, true, null, entrySchema, null); + DataModelUtil.addInputParameterToTopologyTemplate(serviceTemplate, parameterId, parameterDefinition); + } + + // Return the input parameter Id which is used in the new property value if there is one + private Optional<String> updateProperty(ServiceTemplate serviceTemplate, String nodeTemplateId, NodeTemplate nodeTemplate, + Map.Entry<String, Object> propertyEntry, UnifiedCompositionEntity compositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + PortTemplateConsolidationData portTemplateConsolidationData, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + if (handleGetAttrFromConsolidationNodes(serviceTemplate, nodeTemplateId, nodeTemplate, propertyEntry, unifiedCompositionDataList, context)) { + return Optional.empty(); + } + String inputParamId = getParameterId(nodeTemplateId, nodeTemplate, propertyEntry.getKey(), compositionEntity, + computeTemplateConsolidationData, portTemplateConsolidationData); + Map<String, List<String>> propertyVal = getPropertyValueInputParam(inputParamId); + nodeTemplate.getProperties().put(propertyEntry.getKey(), propertyVal); + return Optional.of(inputParamId); + } + + private Map<String, List<String>> getPropertyValueInputParam(String inputParamId) { + Map<String, List<String>> propertyVal = new HashMap<>(); + List<String> getInputFuncParams = new ArrayList<>(); + getInputFuncParams.add(inputParamId); + getInputFuncParams.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); + propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), getInputFuncParams); + return propertyVal; + } + + private boolean handleGetAttrFromConsolidationNodes(ServiceTemplate serviceTemplate, String nodeTemplateId, NodeTemplate nodeTemplate, + Map.Entry<String, Object> propertyEntry, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType = getAllConsolidationNodeTemplateIdAndType( + unifiedCompositionDataList); + Set<String> consolidationNodeTemplateIds = consolidationNodeTemplateIdAndType.keySet(); + Map<String, String> entityIdToType = ConsolidationService.getConsolidationEntityIdToType(serviceTemplate, context.getConsolidationData()); + boolean includeGetAttrFromConsolidationNodes = false; + boolean includeGetAttrFromOutsideNodes = false; + boolean isGetAttrFromConsolidationIsFromSameType = false; + List<List<Object>> getAttrFunctionList = extractGetAttrFunction(propertyEntry.getValue()); + for (List<Object> getAttrFunc : getAttrFunctionList) { + String getAttrNodeId = (String) getAttrFunc.get(0); + if (consolidationNodeTemplateIds.contains(getAttrNodeId)) { + includeGetAttrFromConsolidationNodes = true; + if (isGetAttrNodeTemplateFromSameType(nodeTemplateId, getAttrNodeId, entityIdToType)) { + isGetAttrFromConsolidationIsFromSameType = true; + } + } else { + includeGetAttrFromOutsideNodes = true; + } + } + if ((includeGetAttrFromConsolidationNodes && includeGetAttrFromOutsideNodes) || (includeGetAttrFromConsolidationNodes && isIncludeToscaFunc( + propertyEntry.getValue(), ToscaFunctions.GET_INPUT))) { + //This case is currently not supported - this property will be ignored + return true; + } else if (includeGetAttrFromConsolidationNodes && !isGetAttrFromConsolidationIsFromSameType) { + Object clonedPropertyValue = getClonedPropertyValue(propertyEntry); + List<List<Object>> clonedGetAttrFuncList = extractGetAttrFunction(clonedPropertyValue); + for (List<Object> getAttrFunc : clonedGetAttrFuncList) { + String targetNodeTemplateId = (String) getAttrFunc.get(0); + if (consolidationNodeTemplateIds.contains(targetNodeTemplateId)) { + updatePropertyGetAttrFunc(serviceTemplate, unifiedCompositionDataList, consolidationNodeTemplateIdAndType, targetNodeTemplateId, + getAttrFunc, context); + } + } + nodeTemplate.getProperties().put(propertyEntry.getKey(), clonedPropertyValue); + return true; + } + return false; + } + + private boolean isGetAttrNodeTemplateFromSameType(String sourceNodeTemplateId, String targetNodeTemplateId, + Map<String, String> nodeTemplateIdToType) { + if (Objects.isNull(nodeTemplateIdToType.get(sourceNodeTemplateId)) || Objects.isNull(nodeTemplateIdToType.get(targetNodeTemplateId))) { + return false; + } + return nodeTemplateIdToType.get(sourceNodeTemplateId).equals(nodeTemplateIdToType.get(targetNodeTemplateId)); + } + + private void updatePropertyGetAttrFunc(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType, String targetNodeTemplateId, + List<Object> getAttrFunc, TranslationContext context) { + UnifiedCompositionEntity targetCompositionEntity = consolidationNodeTemplateIdAndType.get(targetNodeTemplateId); + String targetNewNodeTemplateId = getNewNodeTemplateId(serviceTemplate, unifiedCompositionDataList, targetNodeTemplateId, + targetCompositionEntity, context); + getAttrFunc.set(0, targetNewNodeTemplateId); + } + + private String getNewNodeTemplateId(ServiceTemplate serviceTemplate, List<UnifiedCompositionData> unifiedCompositionDataList, + String nodeTemplateId, UnifiedCompositionEntity compositionEntity, TranslationContext context) { + String newNodeTemplateId = nodeTemplateId; + String nodeTemplateIdGeneratorImpl = unifiedSubstitutionNodeTemplateIdGeneratorImplMap.get(compositionEntity); + UnifiedSubstitutionNodeTemplateIdGenerator nodeTemplateIdGenerator = CommonMethods + .newInstance(nodeTemplateIdGeneratorImpl, UnifiedSubstitutionNodeTemplateIdGenerator.class); + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, null, unifiedCompositionDataList, context, null); + Optional<String> generatedNodeTemplateId = nodeTemplateIdGenerator.generate(unifiedCompositionTo, nodeTemplateId); + if (generatedNodeTemplateId.isPresent()) { + newNodeTemplateId = generatedNodeTemplateId.get(); + } + return newNodeTemplateId; + } + private String getNewNodeTemplateId(String origNodeTemplateId, String serviceTemplateFileName, ServiceTemplate serviceTemplate, + TranslationContext context) { + ConsolidationData consolidationData = context.getConsolidationData(); + if (isIdIsOfExpectedType(origNodeTemplateId, UnifiedCompositionEntity.PORT, serviceTemplateFileName, context)) { + return handleIdOfPort(origNodeTemplateId, serviceTemplateFileName, consolidationData); + } else if (isIdIsOfExpectedType(origNodeTemplateId, COMPUTE, serviceTemplateFileName, context)) { + NodeTemplate nodeTemplate = getComputeNodeTemplate(origNodeTemplateId, serviceTemplate, context); + return getComputeTypeSuffix(nodeTemplate.getType()); + } + return null; + } + + private Object getClonedPropertyValue(Map.Entry<String, Object> propertyEntry) { + if (propertyEntry.getValue() instanceof Map) { + return getClonedObject(propertyEntry.getValue(), Map.class); + } else if (propertyEntry.getValue() instanceof List) { + return getClonedObject(propertyEntry.getValue(), List.class); + } + return propertyEntry.getValue(); + } + + private String getParameterId(String nodeTemplateId, NodeTemplate nodeTemplate, String propertyId, + UnifiedCompositionEntity unifiedCompositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + PortTemplateConsolidationData portTemplateConsolidationData) { + String paramterId = propertyId; + switch (unifiedCompositionEntity) { + case COMPUTE: + paramterId = COMPUTE.getDisplayName().toLowerCase() + "_" + getComputeTypeSuffix(nodeTemplate.getType()) + "_" + propertyId; + break; + case PORT: + String portType = portTemplateConsolidationData.getPortType(); + if (Objects.isNull(computeTemplateConsolidationData) || (computeTemplateConsolidationData.getPorts().get(portType) != null + && computeTemplateConsolidationData.getPorts().get(portType).size() > 1)) { + paramterId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + nodeTemplateId + "_" + propertyId; + } else { + paramterId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + portType + "_" + propertyId; + } + break; + case SUB_INTERFACE: + paramterId = getSubInterfaceInputParameterId(nodeTemplate.getType(), nodeTemplateId, propertyId, portTemplateConsolidationData); + break; + default: + break; + } + return paramterId; + } + + private String getSubInterfaceInputParameterId(String type, String nodeTemplateId, String propertyId, + PortTemplateConsolidationData portTemplateConsolidationData) { + String subInterfaceType = getSubInterfaceTypeSuffix(type); + if (Objects.isNull(portTemplateConsolidationData) || portTemplateConsolidationData.isSubInterfaceNodeTemplateIdParameter(type)) { + return UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_" + nodeTemplateId + "_" + propertyId; + } + return UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_" + subInterfaceType + "_" + propertyId; + } + + private void removeConnectivityOut(EntityConsolidationData entityConsolidationData, NodeTemplate nodeTemplate) { + Multimap<String, RequirementAssignmentData> nodesConnectedOut = entityConsolidationData.getNodesConnectedOut(); + if (CommonUtil.isMultimapEmpty(nodesConnectedOut)) { + return; + } + nodesConnectedOut.values().forEach(requirementAssignmentData -> DataModelUtil + .removeRequirementsAssignment(nodeTemplate.getRequirements(), requirementAssignmentData.getRequirementId())); if (nodeTemplate.getRequirements().isEmpty()) { nodeTemplate.setRequirements(null); } } - private void removeVolumeConnectivity(ComputeTemplateConsolidationData computeTemplateConsolidationData, - NodeTemplate computeNodeTemplate) { + private void removeVolumeConnectivity(ComputeTemplateConsolidationData computeTemplateConsolidationData, NodeTemplate computeNodeTemplate) { if (CommonUtil.isMultimapEmpty(computeTemplateConsolidationData.getVolumes())) { return; } - - computeTemplateConsolidationData.getVolumes().values().forEach(requirementAssignmentData -> - DataModelUtil.removeRequirementsAssignment(computeNodeTemplate.getRequirements(), - requirementAssignmentData.getRequirementId()) - ); - + computeTemplateConsolidationData.getVolumes().values().forEach(requirementAssignmentData -> DataModelUtil + .removeRequirementsAssignment(computeNodeTemplate.getRequirements(), requirementAssignmentData.getRequirementId())); if (computeNodeTemplate.getRequirements().isEmpty()) { computeNodeTemplate.setRequirements(null); } } - private void createIndexInputParameter(ServiceTemplate substitutionServiceTemplate) { - ParameterDefinition indexParameterDefinition = - DataModelUtil.createParameterDefinition(PropertyType.INTEGER.getDisplayName(), - "Index value of this substitution service template runtime instance", - false, createIndexValueConstraint(), null, 0); - DataModelUtil.addInputParameterToTopologyTemplate(substitutionServiceTemplate, - ToscaConstants.INDEX_VALUE_PROPERTY_NAME, indexParameterDefinition); - } - - - private List<Constraint> createIndexValueConstraint() { - List<Constraint> constraints; - constraints = new ArrayList<>(); - Constraint constraint = new Constraint(); - constraint.setGreater_or_equal(0); - constraints.add(constraint); - return constraints; - } - - private Optional<UnifiedComposition> getUnifiedCompositionInstance(UnifiedCompositionMode mode) { - String unifiedCompositionImplClassName = - unifiedCompositionImplMap.get(mode.name()).getImplementationClass(); - if (StringUtils.isEmpty(unifiedCompositionImplClassName)) { - return Optional.empty(); - } - return Optional - .of(CommonMethods.newInstance(unifiedCompositionImplClassName, UnifiedComposition.class)); - } - - private Optional<Map<String, Object>> createAbstractSubstitutionProperties( - ServiceTemplate serviceTemplate, - Map<String, ParameterDefinition> substitutionTemplateInputs, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - Map<String, Object> abstractSubstituteProperties = new LinkedHashMap<>(); - //Since all the computes have the same type fetching the type from the first entry - NodeTemplate firstComputeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - unifiedCompositionDataList.get(0) - .getComputeTemplateConsolidationData().getNodeTemplateId()); - String computeType = getComputeTypeSuffix(firstComputeNodeTemplate.getType()); - for (Map.Entry<String, ParameterDefinition> input : substitutionTemplateInputs.entrySet()) { - String substitutionTemplateInputName = input.getKey(); - ParameterDefinition inputParameterDefinition = input.getValue(); - String inputType = inputParameterDefinition.getType(); - UnifiedCompositionEntity inputUnifiedCompositionEntity = - getInputCompositionEntity(substitutionTemplateInputName); - - if (isIdenticalValueProperty(substitutionTemplateInputName, inputUnifiedCompositionEntity) - || !inputType.equalsIgnoreCase(PropertyType.LIST.getDisplayName())) { - //Handle identical value properties - Optional<String> identicalValuePropertyName = - getIdenticalValuePropertyName(substitutionTemplateInputName, - inputUnifiedCompositionEntity); - - identicalValuePropertyName.ifPresent(propertyName -> updateIdenticalPropertyValue(propertyName, - substitutionTemplateInputName, inputUnifiedCompositionEntity, - unifiedCompositionDataList.get(0), serviceTemplate, abstractSubstituteProperties, - context)); - continue; - } - - //Check if the input is of type compute, port or sub interface - List<Object> abstractPropertyValue = new ArrayList<>(); - switch (inputUnifiedCompositionEntity) { - case COMPUTE: - createAbstractComputeProperties(unifiedCompositionDataList, - substitutionTemplateInputName, serviceTemplate, abstractPropertyValue); - break; - case PORT: - createAbstractPortProperties(unifiedCompositionDataList, substitutionTemplateInputName, - computeType, serviceTemplate, abstractPropertyValue); - break; - case SUB_INTERFACE: - createAbstractSubInterfaceProperties(unifiedCompositionDataList, - substitutionTemplateInputName, serviceTemplate, abstractPropertyValue); - break; - default: - break; - } - //Add the property only if it has at least one non-null value - if (abstractPropertyValue.stream().anyMatch(Objects::nonNull)) { - updateAbstractPropertyValue(substitutionTemplateInputName, inputParameterDefinition, - abstractPropertyValue, abstractSubstituteProperties); - } - } - return Optional.ofNullable(abstractSubstituteProperties); - } - - private void createAbstractComputeProperties(List<UnifiedCompositionData> - unifiedCompositionDataList, - String substitutionTemplateInputName, - ServiceTemplate serviceTemplate, - List<Object> abstractPropertyValue) { - for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - compositionData.getComputeTemplateConsolidationData(); - Object propertyValue = getComputePropertyValue(substitutionTemplateInputName, - serviceTemplate, computeTemplateConsolidationData); - if (!(propertyValue instanceof Optional)) { - abstractPropertyValue.add(propertyValue); - } - } - } - - private void createAbstractPortProperties(List<UnifiedCompositionData> - unifiedCompositionDataList, - String substitutionTemplateInputName, - String computeType, - ServiceTemplate serviceTemplate, - List<Object> abstractPropertyValue) { - for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(compositionData); - //Get the input type for this input whether it is of type - // port_<port_node_template_id>_<property_name> or port_<port_type>_<property_name> - PropertyInputType portInputType = getPortInputType(substitutionTemplateInputName, - compositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - //Get the port property value - String portNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); - Object propertyValue = getPortPropertyValue(substitutionTemplateInputName, - computeType, portInputType, serviceTemplate, - portNodeTemplateId, portTemplateConsolidationData); - //If the value object is Optional.empty it implies that the property name was not - // found in the input name - if (!(propertyValue instanceof Optional)) { - abstractPropertyValue.add(propertyValue); - } - } - } - } - - private void createAbstractSubInterfaceProperties(List<UnifiedCompositionData> - unifiedCompositionDataList, - String substitutionTemplateInputName, - ServiceTemplate serviceTemplate, - List<Object> abstractPropertyValue) { - for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(compositionData); - //Get the input type for this input whether it is of type - // subInterface_<subinterface_node_template_id>_<property_name> or - // subInterface_<subinterface_type>_<property_name> - PropertyInputType subInterfaceInputType = - getSubInterfaceInputType(substitutionTemplateInputName, compositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - //Get the subInterface property value - String subInterfaceNodeTemplateId = subInterfaceTemplateConsolidationData - .getNodeTemplateId(); - NodeTemplate subInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - subInterfaceNodeTemplateId); - String subInterfaceType = getSubInterfaceTypeSuffix(subInterfaceNodeTemplate - .getType()); - Object propertyValue = getSubInterfacePropertyValue(substitutionTemplateInputName, - subInterfaceType, subInterfaceInputType, serviceTemplate, - subInterfaceNodeTemplateId); - //If the value object is Optional.empty it implies that the property name was not - // found in the input name - if (!(propertyValue instanceof Optional)) { - abstractPropertyValue.add(propertyValue); - } - } - } - } - - private void updateAbstractPropertyValue(String substitutionTemplateInputName, - ParameterDefinition parameterDefinition, - List<Object> abstractPropertyValue, - Map<String, Object> abstractSubstituteProperties) { - if (abstractPropertyValue.size() > 1) { - abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); - } else { - Object propertyValue = abstractPropertyValue.get(0); - String entrySchemaType = parameterDefinition.getEntry_schema().getType(); - if (PropertyType.getSimplePropertyTypes().contains(entrySchemaType.toLowerCase()) - || entrySchemaType.equals(PropertyTypeExt.JSON.getDisplayName())) { - abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); - } else { - abstractSubstituteProperties.put(substitutionTemplateInputName, propertyValue); - } - } - } - - private void updateIdenticalPropertyValue(String identicalValuePropertyName, - String substitutionTemplateInputName, - UnifiedCompositionEntity entity, - UnifiedCompositionData unifiedCompositionData, - ServiceTemplate serviceTemplate, - Map<String, Object> abstractSubstituteProperties, - TranslationContext context) { - Optional<Object> identicalPropertyValueByType = - getIdenticalPropertyValueByType(identicalValuePropertyName, substitutionTemplateInputName, - entity, unifiedCompositionData, serviceTemplate, context); - - if (identicalPropertyValueByType.isPresent()) { - abstractSubstituteProperties - .put(substitutionTemplateInputName, identicalPropertyValueByType.get()); - - } - - - } - - private Optional<Object> getIdenticalPropertyValueByType(String identicalValuePropertyName, - String substitutionTemplateInputName, - UnifiedCompositionEntity entity, - UnifiedCompositionData - unifiedCompositionData, - ServiceTemplate serviceTemplate, - TranslationContext context) { - - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - - Optional<Object> identicalPropertyValue = Optional.empty(); - switch (entity) { - case COMPUTE: - identicalPropertyValue = - getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, - computeTemplateConsolidationData, context); - break; - case OTHER: - identicalPropertyValue = - getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, - computeTemplateConsolidationData, context); - break; - case PORT: - PropertyInputType portInputType = getPortInputType(substitutionTemplateInputName, - unifiedCompositionData); - Optional <PortTemplateConsolidationData> portTemplateConsolidationData = - unifiedCompositionData.getPortTemplateConsolidationDataList() - .stream() - .filter(s -> substitutionTemplateInputName. - contains(getPropertyInputPrefix(s.getNodeTemplateId(), - s.getPortType(), - portInputType, UnifiedCompositionEntity.PORT))) - .findFirst(); - - if(portTemplateConsolidationData.isPresent()) { - return getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, - portTemplateConsolidationData.get(), context); - } - break; - default: - break; - } - return identicalPropertyValue; - } - - - private PropertyInputType getPortInputType(String inputName, - UnifiedCompositionData unifiedCompositionData) { - String portInputPrefix = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_"; - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - //Scan the available port node template ids to check if the input is of the form - // "port_<port_node_template_id>_<property_name>" - if (portTemplateConsolidationDataList.stream().map(EntityConsolidationData::getNodeTemplateId) - .map(portNodeTemplateId -> portInputPrefix + portNodeTemplateId).anyMatch(inputName::startsWith)) { - return PropertyInputType.NODE_TEMPLATE_ID; - } - //Check whether the input is of the form "port_<port_type>_<property_name>" - Set<String> portTypes = computeTemplateConsolidationData.getPorts().keySet(); - if (portTypes.stream().map(portType -> portInputPrefix + portType + "_").anyMatch(inputName::startsWith)) { - return PropertyInputType.TYPE; - } - return PropertyInputType.OTHER; - } - - private PropertyInputType getSubInterfaceInputType(String inputName, - UnifiedCompositionData unifiedCompositionData) { - String subInterfaceInputPrefix = UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() - + "_"; - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - //Scan the available port node template ids to check if the input is of the form - // "subinterface_<subinterface_node_template_id>_<property_name>" - if (subInterfaceTemplateConsolidationDataList.stream().map(EntityConsolidationData::getNodeTemplateId) - .map(subInterfaceNodeTemplateId -> subInterfaceInputPrefix - + subInterfaceNodeTemplateId) - .anyMatch(inputName::startsWith)) { - return PropertyInputType.NODE_TEMPLATE_ID; - } - //Check whether the input is of the form "subinterface_<subinterface_type>_<property_name>" - Set<String> subInterfaceTypes = new HashSet<>(); - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceTypeToEntity = ArrayListMultimap.create(); - portTemplateConsolidationData.copyMappedInto(subInterfaceTypeToEntity); - subInterfaceTypes.addAll(subInterfaceTypeToEntity.keySet()); - } - - if (subInterfaceTypes.stream().map(UnifiedCompositionUtil::getSubInterfaceTypeSuffix) - .map(subInterfaceTypeSuffix -> subInterfaceInputPrefix + subInterfaceTypeSuffix + "_") - .anyMatch(inputName::startsWith)) { - return PropertyInputType.TYPE; - } - return PropertyInputType.OTHER; - } - - private void cleanServiceTemplate(ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - removeNodeTemplateFromServiceTemplate(serviceTemplate, entity, context); - updateHeatStackGroup(serviceTemplate, entity, context); - updateSubstitutionMapping(serviceTemplate, context); - } + private void createIndexInputParameter(ServiceTemplate substitutionServiceTemplate) { + ParameterDefinition indexParameterDefinition = DataModelUtil + .createParameterDefinition(PropertyType.INTEGER.getDisplayName(), "Index value of this substitution service template runtime instance", + false, createIndexValueConstraint(), null, 0); + DataModelUtil + .addInputParameterToTopologyTemplate(substitutionServiceTemplate, ToscaConstants.INDEX_VALUE_PROPERTY_NAME, indexParameterDefinition); + } - private void removeNodeTemplateFromServiceTemplate(ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - String nodeTemplateIdToRemove = entity.getNodeTemplateId(); - Map<String, NodeTemplate> nodeTemplates = - serviceTemplate.getTopology_template().getNode_templates(); - NodeTemplate nodeTemplateToRemove = - nodeTemplates.get(nodeTemplateIdToRemove); - nodeTemplates.remove(nodeTemplateIdToRemove); - - context.addCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - nodeTemplateIdToRemove, - entity.getClass() == ComputeTemplateConsolidationData.class - ? COMPUTE - : UnifiedCompositionEntity.PORT, - nodeTemplateToRemove); - - } - - private void removeCleanedNodeType(String cleanedNodeTemplateId, - ServiceTemplate serviceTemplate, - TranslationContext context) { - NodeTemplate cleanedNodeTemplate = - context - .getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - cleanedNodeTemplateId); - String typeToRemove = cleanedNodeTemplate.getType(); + private List<Constraint> createIndexValueConstraint() { + List<Constraint> constraints; + constraints = new ArrayList<>(); + Constraint constraint = new Constraint(); + constraint.setGreater_or_equal(0); + constraints.add(constraint); + return constraints; + } + + private Optional<UnifiedComposition> getUnifiedCompositionInstance(UnifiedCompositionMode mode) { + String unifiedCompositionImplClassName = unifiedCompositionImplMap.get(mode.name()).getImplementationClass(); + if (StringUtils.isEmpty(unifiedCompositionImplClassName)) { + return Optional.empty(); + } + return Optional.of(CommonMethods.newInstance(unifiedCompositionImplClassName, UnifiedComposition.class)); + } + + private Optional<Map<String, Object>> createAbstractSubstitutionProperties(ServiceTemplate serviceTemplate, + Map<String, ParameterDefinition> substitutionTemplateInputs, + List<UnifiedCompositionData> unifiedCompositionDataList, + TranslationContext context) { + Map<String, Object> abstractSubstituteProperties = new LinkedHashMap<>(); + //Since all the computes have the same type fetching the type from the first entry + NodeTemplate firstComputeNodeTemplate = DataModelUtil + .getNodeTemplate(serviceTemplate, unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData().getNodeTemplateId()); + String computeType = getComputeTypeSuffix(firstComputeNodeTemplate.getType()); + for (Map.Entry<String, ParameterDefinition> input : substitutionTemplateInputs.entrySet()) { + String substitutionTemplateInputName = input.getKey(); + ParameterDefinition inputParameterDefinition = input.getValue(); + String inputType = inputParameterDefinition.getType(); + UnifiedCompositionEntity inputUnifiedCompositionEntity = getInputCompositionEntity(substitutionTemplateInputName); + if (isIdenticalValueProperty(substitutionTemplateInputName, inputUnifiedCompositionEntity) || !inputType + .equalsIgnoreCase(PropertyType.LIST.getDisplayName())) { + //Handle identical value properties + Optional<String> identicalValuePropertyName = getIdenticalValuePropertyName(substitutionTemplateInputName, + inputUnifiedCompositionEntity); + identicalValuePropertyName.ifPresent( + propertyName -> updateIdenticalPropertyValue(propertyName, substitutionTemplateInputName, inputUnifiedCompositionEntity, + unifiedCompositionDataList.get(0), serviceTemplate, abstractSubstituteProperties, context)); + continue; + } + //Check if the input is of type compute, port or sub interface + List<Object> abstractPropertyValue = new ArrayList<>(); + switch (inputUnifiedCompositionEntity) { + case COMPUTE: + createAbstractComputeProperties(unifiedCompositionDataList, substitutionTemplateInputName, serviceTemplate, + abstractPropertyValue); + break; + case PORT: + createAbstractPortProperties(unifiedCompositionDataList, substitutionTemplateInputName, computeType, serviceTemplate, + abstractPropertyValue); + break; + case SUB_INTERFACE: + createAbstractSubInterfaceProperties(unifiedCompositionDataList, substitutionTemplateInputName, serviceTemplate, + abstractPropertyValue); + break; + default: + break; + } + //Add the property only if it has at least one non-null value + if (abstractPropertyValue.stream().anyMatch(Objects::nonNull)) { + updateAbstractPropertyValue(substitutionTemplateInputName, inputParameterDefinition, abstractPropertyValue, + abstractSubstituteProperties); + } + } + return Optional.ofNullable(abstractSubstituteProperties); + } - if (Objects.nonNull(typeToRemove) - && serviceTemplate.getNode_types().containsKey(typeToRemove)) { - serviceTemplate.getNode_types().remove(typeToRemove); + private void createAbstractComputeProperties(List<UnifiedCompositionData> unifiedCompositionDataList, String substitutionTemplateInputName, + ServiceTemplate serviceTemplate, List<Object> abstractPropertyValue) { + for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = compositionData.getComputeTemplateConsolidationData(); + Object propertyValue = getComputePropertyValue(substitutionTemplateInputName, serviceTemplate, computeTemplateConsolidationData); + if (!(propertyValue instanceof Optional)) { + abstractPropertyValue.add(propertyValue); + } + } } - } - private void updateHeatStackGroup(ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - Map<String, GroupDefinition> groups = serviceTemplate.getTopology_template() - .getGroups() == null ? new HashMap<>() - : serviceTemplate.getTopology_template().getGroups(); - String nodeRelatedAbstractNodeId = - context.getUnifiedAbstractNodeTemplateId(serviceTemplate, entity.getNodeTemplateId()); - - for (Map.Entry<String, GroupDefinition> groupEntry : groups.entrySet()) { - GroupDefinition groupDefinition = groupEntry.getValue(); - if (isHeatStackGroup(groupDefinition.getType())) { - updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nodeRelatedAbstractNodeId, - groupEntry); - } - } - } - - private void updateGroupMembersWithNewUnifiedNodeTemplateId( - EntityConsolidationData entity, - String newNodetemplateId, - Map.Entry<String, GroupDefinition> groupEntry) { - List<String> members = groupEntry.getValue().getMembers(); - if (members.contains(entity.getNodeTemplateId())) { - members.remove(entity.getNodeTemplateId()); - if (!members.contains(newNodetemplateId)) { - members.add(newNodetemplateId); - } - } - groupEntry.getValue().setMembers(members); - } - - private void updateSubstitutionMapping(ServiceTemplate serviceTemplate, - TranslationContext context) { - SubstitutionMapping substitutionMappings = - DataModelUtil.getSubstitutionMappings(serviceTemplate); - if (Objects.nonNull(substitutionMappings)) { + private void createAbstractPortProperties(List<UnifiedCompositionData> unifiedCompositionDataList, String substitutionTemplateInputName, + String computeType, ServiceTemplate serviceTemplate, List<Object> abstractPropertyValue) { + for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(compositionData); + //Get the input type for this input whether it is of type + + // port_<port_node_template_id>_<property_name> or port_<port_type>_<property_name> + PropertyInputType portInputType = getPortInputType(substitutionTemplateInputName, compositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + //Get the port property value + String portNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); + Object propertyValue = getPortPropertyValue(substitutionTemplateInputName, computeType, portInputType, serviceTemplate, + portNodeTemplateId, portTemplateConsolidationData); + //If the value object is Optional.empty it implies that the property name was not + + // found in the input name + if (!(propertyValue instanceof Optional)) { + abstractPropertyValue.add(propertyValue); + } + } + } + } - if (Objects.nonNull(substitutionMappings.getRequirements())) { - updateSubstitutionMappingRequirements(substitutionMappings.getRequirements(), - serviceTemplate, context); - } + private void createAbstractSubInterfaceProperties(List<UnifiedCompositionData> unifiedCompositionDataList, String substitutionTemplateInputName, + ServiceTemplate serviceTemplate, List<Object> abstractPropertyValue) { + for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + compositionData); + //Get the input type for this input whether it is of type + + // subInterface_<subinterface_node_template_id>_<property_name> or + + // subInterface_<subinterface_type>_<property_name> + PropertyInputType subInterfaceInputType = getSubInterfaceInputType(substitutionTemplateInputName, compositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + //Get the subInterface property value + String subInterfaceNodeTemplateId = subInterfaceTemplateConsolidationData.getNodeTemplateId(); + NodeTemplate subInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, subInterfaceNodeTemplateId); + String subInterfaceType = getSubInterfaceTypeSuffix(subInterfaceNodeTemplate.getType()); + Object propertyValue = getSubInterfacePropertyValue(substitutionTemplateInputName, subInterfaceType, subInterfaceInputType, + serviceTemplate, subInterfaceNodeTemplateId); + //If the value object is Optional.empty it implies that the property name was not + + // found in the input name + if (!(propertyValue instanceof Optional)) { + abstractPropertyValue.add(propertyValue); + } + } + } + } - if (Objects.nonNull(substitutionMappings.getCapabilities())) { - updateSubstitutionMappingCapabilities(substitutionMappings.getCapabilities(), - serviceTemplate, context); - } + private void updateAbstractPropertyValue(String substitutionTemplateInputName, ParameterDefinition parameterDefinition, + List<Object> abstractPropertyValue, Map<String, Object> abstractSubstituteProperties) { + if (abstractPropertyValue.size() > 1) { + abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); + } else { + Object propertyValue = abstractPropertyValue.get(0); + String entrySchemaType = parameterDefinition.getEntry_schema().getType(); + if (PropertyType.getSimplePropertyTypes().contains(entrySchemaType.toLowerCase()) || entrySchemaType + .equals(PropertyTypeExt.JSON.getDisplayName())) { + abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); + } else { + abstractSubstituteProperties.put(substitutionTemplateInputName, propertyValue); + } + } } - } - private void updateSubstitutionMappingRequirements(Map<String, List<String>> - substitutionMappingRequirements, - ServiceTemplate serviceTemplate, - TranslationContext context) { - for (Map.Entry<String, List<String>> entry : substitutionMappingRequirements.entrySet()) { - List<String> requirement = entry.getValue(); - String oldNodeTemplateId = requirement.get(0); - String newAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, - requirement.get(0)); - String newSubstitutionNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId( - serviceTemplate, oldNodeTemplateId); - if (Objects.nonNull(newAbstractNodeTemplateId) - && Objects.nonNull(newSubstitutionNodeTemplateId)) { - requirement.set(0, newAbstractNodeTemplateId); - String newRequirementValue = requirement.get(1) + "_" + newSubstitutionNodeTemplateId; - requirement.set(1, newRequirementValue); - } - } - } - - private void updateSubstitutionMappingCapabilities(Map<String, List<String>> - substitutionMappingCapabilities, - ServiceTemplate serviceTemplate, - TranslationContext context) { - for (Map.Entry<String, List<String>> entry : substitutionMappingCapabilities.entrySet()) { - List<String> capability = entry.getValue(); - String oldNodeTemplateId = capability.get(0); - String newAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, - capability.get(0)); - String newSubstitutionNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId( - serviceTemplate, oldNodeTemplateId); - if (Objects.nonNull(newAbstractNodeTemplateId) - && Objects.nonNull(newSubstitutionNodeTemplateId)) { - capability.set(0, newAbstractNodeTemplateId); - String newRequirementValue = capability.get(1) + "_" + newSubstitutionNodeTemplateId; - capability.set(1, newRequirementValue); - } - } - } - - private void updateHeatStackGroupNestedComposition(ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - Map<String, GroupDefinition> groups = serviceTemplate.getTopology_template() - .getGroups() == null ? new HashMap<>() : serviceTemplate.getTopology_template().getGroups(); - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - Optional<String> nestedNodeTemplateId = - context.getUnifiedNestedNodeTemplateId(serviceTemplateFileName, entity.getNodeTemplateId()); - if (nestedNodeTemplateId.isPresent()) { - for (Map.Entry<String, GroupDefinition> groupEntry : groups.entrySet()) { - GroupDefinition groupDefinition = groupEntry.getValue(); - if (isHeatStackGroup(groupDefinition.getType())) { - updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nestedNodeTemplateId.get(), - groupEntry); - } - } - } - } - - private void handleNestedNodeTemplateInMainServiceTemplate(String nestedNodeTemplateId, - ServiceTemplate mainServiceTemplate, - ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - NodeTemplate nestedNodeTemplate = DataModelUtil.getNodeTemplate(mainServiceTemplate, - nestedNodeTemplateId); - if (Objects.isNull(nestedNodeTemplate)) { - return; - } - - updateNestedNodeTemplateProperties(nestedServiceTemplate, nestedNodeTemplate, context); - - Optional<String> unifiedNestedNodeTypeId = context - .getUnifiedNestedNodeTypeId( - ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME), - nestedNodeTemplate.getType()); - unifiedNestedNodeTypeId - .ifPresent(unifiedNestedNodeTypeIdVal -> updateNestedNodeTemplate( - unifiedNestedNodeTypeIdVal, nestedNodeTemplateId, nestedNodeTemplate, - mainServiceTemplate, context)); - } - - private void updateNestedNodeTemplateProperties(ServiceTemplate nestedServiceTemplate, - NodeTemplate nestedNodeTemplate, - TranslationContext context) { + private void updateIdenticalPropertyValue(String identicalValuePropertyName, String substitutionTemplateInputName, + UnifiedCompositionEntity entity, UnifiedCompositionData unifiedCompositionData, + ServiceTemplate serviceTemplate, Map<String, Object> abstractSubstituteProperties, + TranslationContext context) { + Optional<Object> identicalPropertyValueByType = getIdenticalPropertyValueByType(identicalValuePropertyName, substitutionTemplateInputName, + entity, unifiedCompositionData, serviceTemplate, context); + if (identicalPropertyValueByType.isPresent()) { + abstractSubstituteProperties.put(substitutionTemplateInputName, identicalPropertyValueByType.get()); + } + } + + private Optional<Object> getIdenticalPropertyValueByType(String identicalValuePropertyName, String substitutionTemplateInputName, + UnifiedCompositionEntity entity, UnifiedCompositionData unifiedCompositionData, + ServiceTemplate serviceTemplate, TranslationContext context) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + Optional<Object> identicalPropertyValue = Optional.empty(); + switch (entity) { + case COMPUTE: + identicalPropertyValue = getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, computeTemplateConsolidationData, + context); + break; + case OTHER: + identicalPropertyValue = getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, computeTemplateConsolidationData, + context); + break; + case PORT: + PropertyInputType portInputType = getPortInputType(substitutionTemplateInputName, unifiedCompositionData); + Optional<PortTemplateConsolidationData> portTemplateConsolidationData = unifiedCompositionData.getPortTemplateConsolidationDataList() + .stream().filter(s -> substitutionTemplateInputName + .contains(getPropertyInputPrefix(s.getNodeTemplateId(), s.getPortType(), portInputType, UnifiedCompositionEntity.PORT))) + .findFirst(); + if (portTemplateConsolidationData.isPresent()) { + return getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, portTemplateConsolidationData.get(), context); + } + break; + default: + break; + } + return identicalPropertyValue; + } - Map<String, Object> newPropertyInputParamIds = - context.getAllNewPropertyInputParamIdsPerNodeTenplateId(ToscaUtil - .getServiceTemplateFileName(nestedServiceTemplate)); + private PropertyInputType getPortInputType(String inputName, UnifiedCompositionData unifiedCompositionData) { + String portInputPrefix = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_"; + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + //Scan the available port node template ids to check if the input is of the form - for (Map.Entry<String, Object> entry : newPropertyInputParamIds.entrySet()) { - if (Objects.nonNull(entry.getValue())) { - Object value = getClonedObject(entry.getValue()); - nestedNodeTemplate.getProperties().put(entry.getKey(), value); - } + // "port_<port_node_template_id>_<property_name>" + if (portTemplateConsolidationDataList.stream().map(EntityConsolidationData::getNodeTemplateId) + .map(portNodeTemplateId -> portInputPrefix + portNodeTemplateId).anyMatch(inputName::startsWith)) { + return PropertyInputType.NODE_TEMPLATE_ID; + } + //Check whether the input is of the form "port_<port_type>_<property_name>" + Set<String> portTypes = computeTemplateConsolidationData.getPorts().keySet(); + if (portTypes.stream().map(portType -> portInputPrefix + portType + "_").anyMatch(inputName::startsWith)) { + return PropertyInputType.TYPE; + } + return PropertyInputType.OTHER; } - String subNodeType = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getNode_type(); - nestedNodeTemplate.setType(subNodeType); + private PropertyInputType getSubInterfaceInputType(String inputName, UnifiedCompositionData unifiedCompositionData) { + String subInterfaceInputPrefix = UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_"; + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + //Scan the available port node template ids to check if the input is of the form - } + // "subinterface_<subinterface_node_template_id>_<property_name>" + if (subInterfaceTemplateConsolidationDataList.stream().map(EntityConsolidationData::getNodeTemplateId) + .map(subInterfaceNodeTemplateId -> subInterfaceInputPrefix + subInterfaceNodeTemplateId).anyMatch(inputName::startsWith)) { + return PropertyInputType.NODE_TEMPLATE_ID; + } + //Check whether the input is of the form "subinterface_<subinterface_type>_<property_name>" + Set<String> subInterfaceTypes = new HashSet<>(); + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceTypeToEntity = ArrayListMultimap.create(); + portTemplateConsolidationData.copyMappedInto(subInterfaceTypeToEntity); + subInterfaceTypes.addAll(subInterfaceTypeToEntity.keySet()); + } + if (subInterfaceTypes.stream().map(UnifiedCompositionUtil::getSubInterfaceTypeSuffix) + .map(subInterfaceTypeSuffix -> subInterfaceInputPrefix + subInterfaceTypeSuffix + "_").anyMatch(inputName::startsWith)) { + return PropertyInputType.TYPE; + } + return PropertyInputType.OTHER; + } - private void handleSubstitutionMappingInNestedServiceTemplate( - String newNestedNodeType, - ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - if (Objects.isNull(newNestedNodeType)) { - return; + private void cleanServiceTemplate(ServiceTemplate serviceTemplate, EntityConsolidationData entity, TranslationContext context) { + removeNodeTemplateFromServiceTemplate(serviceTemplate, entity, context); + updateHeatStackGroup(serviceTemplate, entity, context); + updateSubstitutionMapping(serviceTemplate, context); } - Set<String> relatedNestedNodeTypeIds = - context.getAllRelatedNestedNodeTypeIds(); + private void removeNodeTemplateFromServiceTemplate(ServiceTemplate serviceTemplate, EntityConsolidationData entity, TranslationContext context) { + String nodeTemplateIdToRemove = entity.getNodeTemplateId(); + Map<String, NodeTemplate> nodeTemplates = serviceTemplate.getTopology_template().getNode_templates(); + NodeTemplate nodeTemplateToRemove = nodeTemplates.get(nodeTemplateIdToRemove); + nodeTemplates.remove(nodeTemplateIdToRemove); + context.addCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), nodeTemplateIdToRemove, + entity.getClass() == ComputeTemplateConsolidationData.class ? COMPUTE : UnifiedCompositionEntity.PORT, nodeTemplateToRemove); + } - SubstitutionMapping substitutionMappings = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); - if (!relatedNestedNodeTypeIds.contains(substitutionMappings.getNode_type())) { - substitutionMappings.setNode_type(newNestedNodeType); + private void removeCleanedNodeType(String cleanedNodeTemplateId, ServiceTemplate serviceTemplate, TranslationContext context) { + NodeTemplate cleanedNodeTemplate = context + .getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), cleanedNodeTemplateId); + String typeToRemove = cleanedNodeTemplate.getType(); + if (Objects.nonNull(typeToRemove) && serviceTemplate.getNode_types().containsKey(typeToRemove)) { + serviceTemplate.getNode_types().remove(typeToRemove); + } } - } - private void updateNestedNodeTemplate(String newNestedNodeTypeId, - String nestedNodeTemplateId, - NodeTemplate nestedNodeTemplate, - ServiceTemplate mainServiceTemplate, - TranslationContext context) { - String mainSTName = ToscaUtil.getServiceTemplateFileName(mainServiceTemplate); - String globalSTName = - ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - int index = - context.getHandledNestedComputeNodeTemplateIndex(globalSTName, newNestedNodeTypeId); - String newNodeTemplateId = - Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX + getComputeTypeSuffix(newNestedNodeTypeId) - + "_" + index; - - nestedNodeTemplate.setType(newNestedNodeTypeId); - mainServiceTemplate.getTopology_template().getNode_templates().remove(nestedNodeTemplateId); - mainServiceTemplate.getTopology_template().getNode_templates() - .put(newNodeTemplateId, nestedNodeTemplate); - - context.addUnifiedNestedNodeTemplateId(mainSTName, nestedNodeTemplateId, newNodeTemplateId); - } - - private void handleNestedNodeTypesInGlobalSubstituteServiceTemplate( - String origNestedNodeTypeId, - String newNestedNodeTypeId, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { - Set<String> relatedNestedNodeTypeIds = - context.getAllRelatedNestedNodeTypeIds(); - - Map<String, NodeType> nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); - if (!relatedNestedNodeTypeIds.contains(origNestedNodeTypeId)) { - NodeType nested = DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, - origNestedNodeTypeId); - setNewValuesForNestedNodeType(origNestedNodeTypeId, newNestedNodeTypeId, nested, nodeTypes); - } else { - NodeType nested = - (NodeType) DataModelUtil.getClonedObject( - DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, origNestedNodeTypeId)); - nested.setDerived_from(ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); - nodeTypes.put(newNestedNodeTypeId, nested); - } - context.addUnifiedNestedNodeTypeId(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, - origNestedNodeTypeId, newNestedNodeTypeId); - } - - private void setNewValuesForNestedNodeType(String origNestedNodeType, - String newNestedNodeTypeId, - NodeType nested, - Map<String, NodeType> nodeTypes) { - if (Objects.nonNull(nested)) { - nested.setDerived_from(ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); - nodeTypes.remove(origNestedNodeType); - nodeTypes.put(newNestedNodeTypeId, nested); - } - } - - private Optional<String> getNewNestedNodeTypeId(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - FileComputeConsolidationData fileComputeConsolidationData = - context.getConsolidationData().getComputeConsolidationData() - .getFileComputeConsolidationData( - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); - - if (Objects.nonNull(fileComputeConsolidationData)) { - String nestedNodeTypePrefix = ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + "heat."; - return Optional - .of(nestedNodeTypePrefix + getComputeTypeInNestedFile(fileComputeConsolidationData)); - } - return Optional.empty(); - } - - private String getComputeTypeInNestedFile( - FileComputeConsolidationData fileComputeConsolidationData) { - List<TypeComputeConsolidationData> typeComputeConsolidationDatas = - new ArrayList<>(fileComputeConsolidationData.getAllTypeComputeConsolidationData()); - if (typeComputeConsolidationDatas.isEmpty()) { - return null; - } else { - String computeNodeType = fileComputeConsolidationData.getAllComputeTypes().iterator().next(); - return getComputeTypeSuffix(computeNodeType); - } - } - - private void handleGetAttrInAbstractNodeTemplate(ServiceTemplate serviceTemplate, - TranslationContext context, - String serviceTemplateFileName, - NodeTemplate abstractNodeTemplate) { - Map<String, Object> properties = - abstractNodeTemplate == null || abstractNodeTemplate.getProperties() == null - ? new HashMap<>() - : abstractNodeTemplate.getProperties(); - for (Object propertyValue : properties.values()) { - List<List<Object>> getAttrList = extractGetAttrFunction(propertyValue); - for (List<Object> getAttrFuncValue : getAttrList) { - String origNodeTemplateId = (String) getAttrFuncValue.get(0); - Optional<String> nestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), origNodeTemplateId); + private void updateHeatStackGroup(ServiceTemplate serviceTemplate, EntityConsolidationData entity, TranslationContext context) { + Map<String, GroupDefinition> groups = + serviceTemplate.getTopology_template().getGroups() == null ? new HashMap<>() : serviceTemplate.getTopology_template().getGroups(); + String nodeRelatedAbstractNodeId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, entity.getNodeTemplateId()); + for (Map.Entry<String, GroupDefinition> groupEntry : groups.entrySet()) { + GroupDefinition groupDefinition = groupEntry.getValue(); + if (isHeatStackGroup(groupDefinition.getType())) { + updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nodeRelatedAbstractNodeId, groupEntry); + } + } + } + + private void updateGroupMembersWithNewUnifiedNodeTemplateId(EntityConsolidationData entity, String newNodetemplateId, + Map.Entry<String, GroupDefinition> groupEntry) { + List<String> members = groupEntry.getValue().getMembers(); + if (members.contains(entity.getNodeTemplateId())) { + members.remove(entity.getNodeTemplateId()); + if (!members.contains(newNodetemplateId)) { + members.add(newNodetemplateId); + } + } + groupEntry.getValue().setMembers(members); + } + + private void updateSubstitutionMapping(ServiceTemplate serviceTemplate, TranslationContext context) { + SubstitutionMapping substitutionMappings = DataModelUtil.getSubstitutionMappings(serviceTemplate); + if (Objects.nonNull(substitutionMappings)) { + if (Objects.nonNull(substitutionMappings.getRequirements())) { + updateSubstitutionMappingRequirements(substitutionMappings.getRequirements(), serviceTemplate, context); + } + if (Objects.nonNull(substitutionMappings.getCapabilities())) { + updateSubstitutionMappingCapabilities(substitutionMappings.getCapabilities(), serviceTemplate, context); + } + } + } + + private void updateSubstitutionMappingRequirements(Map<String, List<String>> substitutionMappingRequirements, ServiceTemplate serviceTemplate, + TranslationContext context) { + for (Map.Entry<String, List<String>> entry : substitutionMappingRequirements.entrySet()) { + List<String> requirement = entry.getValue(); + String oldNodeTemplateId = requirement.get(0); + String newAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, requirement.get(0)); + String newSubstitutionNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId(serviceTemplate, oldNodeTemplateId); + if (Objects.nonNull(newAbstractNodeTemplateId) && Objects.nonNull(newSubstitutionNodeTemplateId)) { + requirement.set(0, newAbstractNodeTemplateId); + String newRequirementValue = requirement.get(1) + "_" + newSubstitutionNodeTemplateId; + requirement.set(1, newRequirementValue); + } + } + } + + private void updateSubstitutionMappingCapabilities(Map<String, List<String>> substitutionMappingCapabilities, ServiceTemplate serviceTemplate, + TranslationContext context) { + for (Map.Entry<String, List<String>> entry : substitutionMappingCapabilities.entrySet()) { + List<String> capability = entry.getValue(); + String oldNodeTemplateId = capability.get(0); + String newAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, capability.get(0)); + String newSubstitutionNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId(serviceTemplate, oldNodeTemplateId); + if (Objects.nonNull(newAbstractNodeTemplateId) && Objects.nonNull(newSubstitutionNodeTemplateId)) { + capability.set(0, newAbstractNodeTemplateId); + String newRequirementValue = capability.get(1) + "_" + newSubstitutionNodeTemplateId; + capability.set(1, newRequirementValue); + } + } + } + + private void updateHeatStackGroupNestedComposition(ServiceTemplate serviceTemplate, EntityConsolidationData entity, TranslationContext context) { + Map<String, GroupDefinition> groups = + serviceTemplate.getTopology_template().getGroups() == null ? new HashMap<>() : serviceTemplate.getTopology_template().getGroups(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional<String> nestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId(serviceTemplateFileName, entity.getNodeTemplateId()); if (nestedNodeTemplateId.isPresent()) { - getAttrFuncValue.set(0, nestedNodeTemplateId.get()); + for (Map.Entry<String, GroupDefinition> groupEntry : groups.entrySet()) { + GroupDefinition groupDefinition = groupEntry.getValue(); + if (isHeatStackGroup(groupDefinition.getType())) { + updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nestedNodeTemplateId.get(), groupEntry); + } + } + } + } + + private void handleNestedNodeTemplateInMainServiceTemplate(String nestedNodeTemplateId, ServiceTemplate mainServiceTemplate, + ServiceTemplate nestedServiceTemplate, TranslationContext context) { + NodeTemplate nestedNodeTemplate = DataModelUtil.getNodeTemplate(mainServiceTemplate, nestedNodeTemplateId); + if (Objects.isNull(nestedNodeTemplate)) { + return; + } + updateNestedNodeTemplateProperties(nestedServiceTemplate, nestedNodeTemplate, context); + Optional<String> unifiedNestedNodeTypeId = context + .getUnifiedNestedNodeTypeId(ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME), + nestedNodeTemplate.getType()); + unifiedNestedNodeTypeId.ifPresent( + unifiedNestedNodeTypeIdVal -> updateNestedNodeTemplate(unifiedNestedNodeTypeIdVal, nestedNodeTemplateId, nestedNodeTemplate, + mainServiceTemplate, context)); + } + + private void updateNestedNodeTemplateProperties(ServiceTemplate nestedServiceTemplate, NodeTemplate nestedNodeTemplate, + TranslationContext context) { + Map<String, Object> newPropertyInputParamIds = context + .getAllNewPropertyInputParamIdsPerNodeTenplateId(ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + for (Map.Entry<String, Object> entry : newPropertyInputParamIds.entrySet()) { + if (Objects.nonNull(entry.getValue())) { + Object value = getClonedObject(entry.getValue()); + nestedNodeTemplate.getProperties().put(entry.getKey(), value); + } + } + String subNodeType = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getNode_type(); + nestedNodeTemplate.setType(subNodeType); + } + + private void handleSubstitutionMappingInNestedServiceTemplate(String newNestedNodeType, ServiceTemplate nestedServiceTemplate, + TranslationContext context) { + if (Objects.isNull(newNestedNodeType)) { + return; + } + Set<String> relatedNestedNodeTypeIds = context.getAllRelatedNestedNodeTypeIds(); + SubstitutionMapping substitutionMappings = nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); + if (!relatedNestedNodeTypeIds.contains(substitutionMappings.getNode_type())) { + substitutionMappings.setNode_type(newNestedNodeType); + } + } + + private void updateNestedNodeTemplate(String newNestedNodeTypeId, String nestedNodeTemplateId, NodeTemplate nestedNodeTemplate, + ServiceTemplate mainServiceTemplate, TranslationContext context) { + String mainSTName = ToscaUtil.getServiceTemplateFileName(mainServiceTemplate); + String globalSTName = ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + int index = context.getHandledNestedComputeNodeTemplateIndex(globalSTName, newNestedNodeTypeId); + String newNodeTemplateId = Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX + getComputeTypeSuffix(newNestedNodeTypeId) + "_" + index; + nestedNodeTemplate.setType(newNestedNodeTypeId); + mainServiceTemplate.getTopology_template().getNode_templates().remove(nestedNodeTemplateId); + mainServiceTemplate.getTopology_template().getNode_templates().put(newNodeTemplateId, nestedNodeTemplate); + context.addUnifiedNestedNodeTemplateId(mainSTName, nestedNodeTemplateId, newNodeTemplateId); + } + + private void handleNestedNodeTypesInGlobalSubstituteServiceTemplate(String origNestedNodeTypeId, String newNestedNodeTypeId, + ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + Set<String> relatedNestedNodeTypeIds = context.getAllRelatedNestedNodeTypeIds(); + Map<String, NodeType> nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); + if (!relatedNestedNodeTypeIds.contains(origNestedNodeTypeId)) { + NodeType nested = DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, origNestedNodeTypeId); + setNewValuesForNestedNodeType(origNestedNodeTypeId, newNestedNodeTypeId, nested, nodeTypes); } else { - replaceGetAttrNodeIdAndAttrName(serviceTemplate, context, serviceTemplateFileName, - getAttrFuncValue); + NodeType nested = (NodeType) DataModelUtil + .getClonedObject(DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, origNestedNodeTypeId)); + nested.setDerived_from(ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); + nodeTypes.put(newNestedNodeTypeId, nested); } - } + context.addUnifiedNestedNodeTypeId(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, origNestedNodeTypeId, newNestedNodeTypeId); } - } - private void replaceGetAttrNodeIdAndAttrName(ServiceTemplate serviceTemplate, - TranslationContext context, - String serviceTemplateFileName, - List<Object> getAttrFuncValue) { - String origNodeTemplateId = (String) getAttrFuncValue.get(0); - String attributeName = (String) getAttrFuncValue.get(1); + private void setNewValuesForNestedNodeType(String origNestedNodeType, String newNestedNodeTypeId, NodeType nested, + Map<String, NodeType> nodeTypes) { + if (Objects.nonNull(nested)) { + nested.setDerived_from(ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); + nodeTypes.remove(origNestedNodeType); + nodeTypes.put(newNestedNodeTypeId, nested); + } + } - String unifiedAbstractNodeTemplateId = - context.getUnifiedAbstractNodeTemplateId(serviceTemplate, origNodeTemplateId); + private Optional<String> getNewNestedNodeTypeId(ServiceTemplate nestedServiceTemplate, TranslationContext context) { + FileComputeConsolidationData fileComputeConsolidationData = context.getConsolidationData().getComputeConsolidationData() + .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + if (Objects.nonNull(fileComputeConsolidationData)) { + String nestedNodeTypePrefix = ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + "heat."; + return Optional.of(nestedNodeTypePrefix + getComputeTypeInNestedFile(fileComputeConsolidationData)); + } + return Optional.empty(); + } - if (Objects.isNull(unifiedAbstractNodeTemplateId)) { - return; + private String getComputeTypeInNestedFile(FileComputeConsolidationData fileComputeConsolidationData) { + List<TypeComputeConsolidationData> typeComputeConsolidationDatas = new ArrayList<>( + fileComputeConsolidationData.getAllTypeComputeConsolidationData()); + if (typeComputeConsolidationDatas.isEmpty()) { + return null; + } else { + String computeNodeType = fileComputeConsolidationData.getAllComputeTypes().iterator().next(); + return getComputeTypeSuffix(computeNodeType); + } } - String newNodeTemplateId = - getNewNodeTemplateId(origNodeTemplateId, serviceTemplateFileName, serviceTemplate, context); + private void handleGetAttrInAbstractNodeTemplate(ServiceTemplate serviceTemplate, TranslationContext context, String serviceTemplateFileName, + NodeTemplate abstractNodeTemplate) { + Map<String, Object> properties = + abstractNodeTemplate == null || abstractNodeTemplate.getProperties() == null ? new HashMap<>() : abstractNodeTemplate.getProperties(); + for (Object propertyValue : properties.values()) { + List<List<Object>> getAttrList = extractGetAttrFunction(propertyValue); + for (List<Object> getAttrFuncValue : getAttrList) { + String origNodeTemplateId = (String) getAttrFuncValue.get(0); + Optional<String> nestedNodeTemplateId = context + .getUnifiedNestedNodeTemplateId(ToscaUtil.getServiceTemplateFileName(serviceTemplate), origNodeTemplateId); + if (nestedNodeTemplateId.isPresent()) { + getAttrFuncValue.set(0, nestedNodeTemplateId.get()); + } else { + replaceGetAttrNodeIdAndAttrName(serviceTemplate, context, serviceTemplateFileName, getAttrFuncValue); + } + } + } + } - String newSubstitutionOutputParameterId = - getNewSubstitutionOutputParameterId(newNodeTemplateId, attributeName); + private void replaceGetAttrNodeIdAndAttrName(ServiceTemplate serviceTemplate, TranslationContext context, String serviceTemplateFileName, + List<Object> getAttrFuncValue) { + String origNodeTemplateId = (String) getAttrFuncValue.get(0); + String attributeName = (String) getAttrFuncValue.get(1); + String unifiedAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, origNodeTemplateId); + if (Objects.isNull(unifiedAbstractNodeTemplateId)) { + return; + } + String newNodeTemplateId = getNewNodeTemplateId(origNodeTemplateId, serviceTemplateFileName, serviceTemplate, context); + String newSubstitutionOutputParameterId = getNewSubstitutionOutputParameterId(newNodeTemplateId, attributeName); + getAttrFuncValue.set(0, unifiedAbstractNodeTemplateId); + getAttrFuncValue.set(1, newSubstitutionOutputParameterId); + } - getAttrFuncValue.set(0, unifiedAbstractNodeTemplateId); - getAttrFuncValue.set(1, newSubstitutionOutputParameterId); - } + private NodeTemplate getComputeNodeTemplate(String origNodeTemplateId, ServiceTemplate serviceTemplate, TranslationContext context) { + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, origNodeTemplateId); + if (computeNodeTemplate == null) { + computeNodeTemplate = context.getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), origNodeTemplateId); + } + return computeNodeTemplate; + } - private NodeTemplate getComputeNodeTemplate(String origNodeTemplateId, - ServiceTemplate serviceTemplate, - TranslationContext context) { - NodeTemplate computeNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, origNodeTemplateId); - if (computeNodeTemplate == null) { - computeNodeTemplate = - context.getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - origNodeTemplateId); - } - return computeNodeTemplate; - } - - private String handleIdOfPort(String origNodeTemplateId, String serviceTemplateFileName, - ConsolidationData consolidationData) { - Optional<Pair<String, ComputeTemplateConsolidationData>> - computeTypeAndComputeTemplateByPortId = - getComputeTypeAndComputeTemplateByPortId(origNodeTemplateId, serviceTemplateFileName, - consolidationData); - if (computeTypeAndComputeTemplateByPortId.isPresent()) { - Pair<String, ComputeTemplateConsolidationData> computeIdToComputeData = - computeTypeAndComputeTemplateByPortId.get(); - return getNewPortNodeTemplateId(origNodeTemplateId, computeIdToComputeData.getKey(), - computeIdToComputeData.getValue()); - } - - return null; - } - - private Optional<Pair<String, ComputeTemplateConsolidationData>> - getComputeTypeAndComputeTemplateByPortId(String portId, String serviceTemplateFileName, - ConsolidationData consolidationData) { - FileComputeConsolidationData fileComputeConsolidationData = - consolidationData.getComputeConsolidationData() - .getFileComputeConsolidationData(serviceTemplateFileName); - Set<String> computeTypes = - fileComputeConsolidationData.getAllComputeTypes(); - - for (String computeType : computeTypes) { - Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationDatas = - fileComputeConsolidationData.getTypeComputeConsolidationData(computeType) - .getAllComputeTemplateConsolidationData(); - - for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDatas) { - if (ConsolidationDataUtil.isComputeReferenceToPortId(compute, portId)) { - return Optional.of(new ImmutablePair<>(computeType, compute)); - } - } - } - - return Optional.empty(); - } - - private boolean isIdIsOfExpectedType(String id, - UnifiedCompositionEntity expectedUnifiedCompositionEntity, - String serviceTemplateFileName, - TranslationContext context) { - UnifiedSubstitutionData unifiedSubstitutionData = - context.getUnifiedSubstitutionData().get(serviceTemplateFileName); - if (Objects.isNull(unifiedSubstitutionData)) { - return false; - } - - UnifiedCompositionEntity actualUnifiedCompositionEntity = - unifiedSubstitutionData.getCleanedNodeTemplateCompositionEntity(id); - - return actualUnifiedCompositionEntity == null ? false - : actualUnifiedCompositionEntity.equals(expectedUnifiedCompositionEntity); - } - - private boolean isHeatStackGroup(String groupType) { - return groupType.equals(ToscaGroupType.HEAT_STACK); - } - - private Object getPortPropertyValue(String inputName, - String computeType, - PropertyInputType portInputType, - ServiceTemplate serviceTemplate, - String portNodeTemplateId, - PortTemplateConsolidationData portTemplateConsolidationData) { - //Get the input prefix to extract the property name from the input name - String portType = portTemplateConsolidationData.getPortType(); - String portInputPrefix = getPropertyInputPrefix( - portNodeTemplateId, portType, portInputType, UnifiedCompositionEntity.PORT); - //Get the property name from the input - Optional<String> propertyName = getPropertyNameFromInput(inputName, - UnifiedCompositionEntity.PORT, computeType, portInputPrefix); - //Get the property value from the node template - if (propertyName.isPresent()) { - NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - portNodeTemplateId); - if (Objects.nonNull(portNodeTemplate)) { - return getPropertyValueFromNodeTemplate(propertyName.get(), portNodeTemplate); - } - } - return Optional.empty(); - } - - private Object getComputePropertyValue( - String inputName, - ServiceTemplate serviceTemplate, - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - String nodeType = getComputeTypeSuffix(nodeTemplate.getType()); - Optional<String> propertyName = - getPropertyNameFromInput(inputName, COMPUTE, nodeType, null); - if (propertyName.isPresent()) { - return getPropertyValueFromNodeTemplate(propertyName.get(), nodeTemplate); - } - return Optional.empty(); - } - - private Object getSubInterfacePropertyValue(String inputName, - String subInterfaceTypeSuffix, - PropertyInputType propertyInputType, - ServiceTemplate serviceTemplate, - String subInterfaceNodeTemplateId) { - //Get the input prefix to extract the property name from the input name - String propertyInputPrefix = getPropertyInputPrefix(subInterfaceNodeTemplateId, - subInterfaceTypeSuffix, propertyInputType, UnifiedCompositionEntity.SUB_INTERFACE); - //Get the property name from the input - Optional<String> propertyName = getPropertyNameFromInput(inputName, - UnifiedCompositionEntity.SUB_INTERFACE, null, propertyInputPrefix); - //Get the property value from the node template - if (propertyName.isPresent()) { - NodeTemplate subInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - subInterfaceNodeTemplateId); - if (Objects.nonNull(subInterfaceNodeTemplate)) { - return getPropertyValueFromNodeTemplate(propertyName.get(), subInterfaceNodeTemplate); - } - } - return Optional.empty(); - } - - private Optional<Object> getIdenticalPropertyValue(String identicalValuePropertyName, - ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - NodeTemplate nodeTemplate = - getNodeTemplate(entity.getNodeTemplateId(), serviceTemplate, context); - - Object propertyValueFromNodeTemplate = - getPropertyValueFromNodeTemplate(identicalValuePropertyName, nodeTemplate); - - return Objects.isNull(propertyValueFromNodeTemplate) ? Optional.empty() - : Optional.of(propertyValueFromNodeTemplate); - } - - private UnifiedCompositionEntity getInputCompositionEntity(String inputName) { - UnifiedCompositionEntity inputCompositionEntity = UnifiedCompositionEntity.OTHER; - if (inputName.indexOf('_') != -1) { - String inputType = inputName.substring(0, inputName.indexOf('_')); - if (inputType.equalsIgnoreCase(COMPUTE.getDisplayName())) { - inputCompositionEntity = COMPUTE; - } else if (inputType.equalsIgnoreCase(UnifiedCompositionEntity.PORT.getDisplayName())) { - inputCompositionEntity = UnifiedCompositionEntity.PORT; - } else if (inputType.equalsIgnoreCase(UnifiedCompositionEntity.SUB_INTERFACE - .getDisplayName())) { - inputCompositionEntity = UnifiedCompositionEntity.SUB_INTERFACE; - } - } - return inputCompositionEntity; - } - - private Optional<String> getPropertyNameFromInput( - String inputName, - UnifiedCompositionEntity compositionEntity, - String entityType, String propertyInputPrefix) { - String propertyName = null; - switch (compositionEntity) { - case COMPUTE: - propertyName = inputName.substring(inputName.lastIndexOf(entityType) - + entityType.length() + 1); - break; - case PORT: - case SUB_INTERFACE: - if (inputName.startsWith(propertyInputPrefix)) { - propertyName = inputName.split(propertyInputPrefix)[1]; - } - break; - default: - break; - } - return Optional.ofNullable(propertyName); - } - - private String getPropertyInputPrefix(String nodeTemplateId, - String propertyEntityType, - PropertyInputType propertyInputType, - UnifiedCompositionEntity unifiedCompositionEntity) { - String propertyInputPrefix = unifiedCompositionEntity.getDisplayName().toLowerCase() + "_"; - if (propertyInputType == PropertyInputType.NODE_TEMPLATE_ID) { - propertyInputPrefix += nodeTemplateId + "_"; - } else if (propertyInputType == PropertyInputType.TYPE) { - propertyInputPrefix += propertyEntityType + "_"; - } - return propertyInputPrefix; - } - - private boolean isIdenticalValueProperty(String inputName, - UnifiedCompositionEntity unifiedCompositionEntity) { - - List<String> identicalValuePropertyList = - consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity); - - StringBuilder builder = getPropertyValueStringBuilder(unifiedCompositionEntity); - if (Objects.isNull(builder)) { - return false; - } - - boolean isMatchingProperty = Pattern.matches(builder.toString(), inputName); - return isMatchingProperty - && isPropertyFromIdenticalValuesList(inputName, unifiedCompositionEntity, - identicalValuePropertyList); - } - - private boolean isPropertyFromIdenticalValuesList(String inputName, - UnifiedCompositionEntity unifiedCompositionEntity, - List<String> identicalValuePropertyList) { - switch (unifiedCompositionEntity) { - case COMPUTE: - case OTHER: - Optional<String> identicalValueProperty = getIdenticalValuePropertyName(inputName, unifiedCompositionEntity); - return identicalValueProperty.filter(identicalValuePropertyList::contains).isPresent(); - - case PORT: - return getPortPropertyNameFromInput(inputName, identicalValuePropertyList).isPresent(); - - default: - return false; + private String handleIdOfPort(String origNodeTemplateId, String serviceTemplateFileName, ConsolidationData consolidationData) { + Optional<Pair<String, ComputeTemplateConsolidationData>> computeTypeAndComputeTemplateByPortId = getComputeTypeAndComputeTemplateByPortId( + origNodeTemplateId, serviceTemplateFileName, consolidationData); + if (computeTypeAndComputeTemplateByPortId.isPresent()) { + Pair<String, ComputeTemplateConsolidationData> computeIdToComputeData = computeTypeAndComputeTemplateByPortId.get(); + return getNewPortNodeTemplateId(origNodeTemplateId, computeIdToComputeData.getKey(), computeIdToComputeData.getValue()); + } + return null; } - } - private Optional<String> getPortPropertyNameFromInput(String inputName, - List<String> identicalValuePropertyList) { - for (String identicalProperty : identicalValuePropertyList) { - if (inputName.endsWith(identicalProperty)) { - return Optional.of(identicalProperty); - } + private Optional<Pair<String, ComputeTemplateConsolidationData>> getComputeTypeAndComputeTemplateByPortId(String portId, + String serviceTemplateFileName, + ConsolidationData consolidationData) { + FileComputeConsolidationData fileComputeConsolidationData = consolidationData.getComputeConsolidationData() + .getFileComputeConsolidationData(serviceTemplateFileName); + Set<String> computeTypes = fileComputeConsolidationData.getAllComputeTypes(); + for (String computeType : computeTypes) { + Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationDatas = fileComputeConsolidationData + .getTypeComputeConsolidationData(computeType).getAllComputeTemplateConsolidationData(); + for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDatas) { + if (ConsolidationDataUtil.isComputeReferenceToPortId(compute, portId)) { + return Optional.of(new ImmutablePair<>(computeType, compute)); + } + } + } + return Optional.empty(); } - return Optional.empty(); - } - private StringBuilder getPropertyValueStringBuilder( - UnifiedCompositionEntity unifiedCompositionEntity) { + private boolean isIdIsOfExpectedType(String id, UnifiedCompositionEntity expectedUnifiedCompositionEntity, String serviceTemplateFileName, + TranslationContext context) { + UnifiedSubstitutionData unifiedSubstitutionData = context.getUnifiedSubstitutionData().get(serviceTemplateFileName); + if (Objects.isNull(unifiedSubstitutionData)) { + return false; + } + UnifiedCompositionEntity actualUnifiedCompositionEntity = unifiedSubstitutionData.getCleanedNodeTemplateCompositionEntity(id); + return actualUnifiedCompositionEntity == null ? false : actualUnifiedCompositionEntity.equals(expectedUnifiedCompositionEntity); + } + + private boolean isHeatStackGroup(String groupType) { + return groupType.equals(ToscaGroupType.HEAT_STACK); + } - switch (unifiedCompositionEntity) { - case COMPUTE: - return getComputePropertyValueStringBuilder(); + private Object getPortPropertyValue(String inputName, String computeType, PropertyInputType portInputType, ServiceTemplate serviceTemplate, + String portNodeTemplateId, PortTemplateConsolidationData portTemplateConsolidationData) { + //Get the input prefix to extract the property name from the input name + String portType = portTemplateConsolidationData.getPortType(); + String portInputPrefix = getPropertyInputPrefix(portNodeTemplateId, portType, portInputType, UnifiedCompositionEntity.PORT); + //Get the property name from the input + Optional<String> propertyName = getPropertyNameFromInput(inputName, UnifiedCompositionEntity.PORT, computeType, portInputPrefix); + //Get the property value from the node template + if (propertyName.isPresent()) { + NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, portNodeTemplateId); + if (Objects.nonNull(portNodeTemplate)) { + return getPropertyValueFromNodeTemplate(propertyName.get(), portNodeTemplate); + } + } + return Optional.empty(); + } - case OTHER: - return getComputePropertyValueStringBuilder(); + private Object getComputePropertyValue(String inputName, ServiceTemplate serviceTemplate, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + String nodeType = getComputeTypeSuffix(nodeTemplate.getType()); + Optional<String> propertyName = getPropertyNameFromInput(inputName, COMPUTE, nodeType, null); + if (propertyName.isPresent()) { + return getPropertyValueFromNodeTemplate(propertyName.get(), nodeTemplate); + } + return Optional.empty(); + } - case PORT: - return getPortPropertyValueStringBuilder(); + private Object getSubInterfacePropertyValue(String inputName, String subInterfaceTypeSuffix, PropertyInputType propertyInputType, + ServiceTemplate serviceTemplate, String subInterfaceNodeTemplateId) { + //Get the input prefix to extract the property name from the input name + String propertyInputPrefix = getPropertyInputPrefix(subInterfaceNodeTemplateId, subInterfaceTypeSuffix, propertyInputType, + UnifiedCompositionEntity.SUB_INTERFACE); + //Get the property name from the input + Optional<String> propertyName = getPropertyNameFromInput(inputName, UnifiedCompositionEntity.SUB_INTERFACE, null, propertyInputPrefix); + //Get the property value from the node template + if (propertyName.isPresent()) { + NodeTemplate subInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, subInterfaceNodeTemplateId); + if (Objects.nonNull(subInterfaceNodeTemplate)) { + return getPropertyValueFromNodeTemplate(propertyName.get(), subInterfaceNodeTemplate); + } + } + return Optional.empty(); + } - case SUB_INTERFACE: - return getSubInterfacePropertyValueStringBuilder(); + private Optional<Object> getIdenticalPropertyValue(String identicalValuePropertyName, ServiceTemplate serviceTemplate, + EntityConsolidationData entity, TranslationContext context) { + NodeTemplate nodeTemplate = getNodeTemplate(entity.getNodeTemplateId(), serviceTemplate, context); + Object propertyValueFromNodeTemplate = getPropertyValueFromNodeTemplate(identicalValuePropertyName, nodeTemplate); + return Objects.isNull(propertyValueFromNodeTemplate) ? Optional.empty() : Optional.of(propertyValueFromNodeTemplate); + } - default: - return null; + private UnifiedCompositionEntity getInputCompositionEntity(String inputName) { + UnifiedCompositionEntity inputCompositionEntity = UnifiedCompositionEntity.OTHER; + if (inputName.indexOf('_') != -1) { + String inputType = inputName.substring(0, inputName.indexOf('_')); + if (inputType.equalsIgnoreCase(COMPUTE.getDisplayName())) { + inputCompositionEntity = COMPUTE; + } else if (inputType.equalsIgnoreCase(UnifiedCompositionEntity.PORT.getDisplayName())) { + inputCompositionEntity = UnifiedCompositionEntity.PORT; + } else if (inputType.equalsIgnoreCase(UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName())) { + inputCompositionEntity = UnifiedCompositionEntity.SUB_INTERFACE; + } + } + return inputCompositionEntity; + } + + private Optional<String> getPropertyNameFromInput(String inputName, UnifiedCompositionEntity compositionEntity, String entityType, + String propertyInputPrefix) { + String propertyName = null; + switch (compositionEntity) { + case COMPUTE: + propertyName = inputName.substring(inputName.lastIndexOf(entityType) + entityType.length() + 1); + break; + case PORT: + case SUB_INTERFACE: + if (inputName.startsWith(propertyInputPrefix)) { + propertyName = inputName.split(propertyInputPrefix)[1]; + } + break; + default: + break; + } + return Optional.ofNullable(propertyName); + } + + private String getPropertyInputPrefix(String nodeTemplateId, String propertyEntityType, PropertyInputType propertyInputType, + UnifiedCompositionEntity unifiedCompositionEntity) { + String propertyInputPrefix = unifiedCompositionEntity.getDisplayName().toLowerCase() + "_"; + if (propertyInputType == PropertyInputType.NODE_TEMPLATE_ID) { + propertyInputPrefix += nodeTemplateId + "_"; + } else if (propertyInputType == PropertyInputType.TYPE) { + propertyInputPrefix += propertyEntityType + "_"; + } + return propertyInputPrefix; } - } - - private StringBuilder getPortPropertyValueStringBuilder() { - StringBuilder builder; - builder = new StringBuilder(PORT_IDENTICAL_VALUE_PROPERTY_PREFIX); - builder.append(".+"); - return builder; - } - - private StringBuilder getComputePropertyValueStringBuilder() { - StringBuilder builder; - builder = new StringBuilder(COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX); - builder.append("[a-z]+"); - builder.append(COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX); - return builder; - } - - private StringBuilder getSubInterfacePropertyValueStringBuilder() { - StringBuilder builder; - builder = new StringBuilder(SUB_INTERFACE_PROPERTY_VALUE_PREFIX); - builder.append(".+"); - return builder; - } - - private Optional<String> getIdenticalValuePropertyName(String input, - UnifiedCompositionEntity - unifiedCompositionEntity) { - switch (unifiedCompositionEntity) { - case COMPUTE: - return Optional.of(input.split("_")[1]); - - case OTHER: - return Optional.of(input.split("_")[1]); - - case PORT: - return getPortPropertyNameFromInput(input, consolidationService - .getPropertiesWithIdenticalVal(unifiedCompositionEntity)); - - default: + + private boolean isIdenticalValueProperty(String inputName, UnifiedCompositionEntity unifiedCompositionEntity) { + List<String> identicalValuePropertyList = consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity); + StringBuilder builder = getPropertyValueStringBuilder(unifiedCompositionEntity); + if (Objects.isNull(builder)) { + return false; + } + boolean isMatchingProperty = Pattern.matches(builder.toString(), inputName); + return isMatchingProperty && isPropertyFromIdenticalValuesList(inputName, unifiedCompositionEntity, identicalValuePropertyList); + } + + private boolean isPropertyFromIdenticalValuesList(String inputName, UnifiedCompositionEntity unifiedCompositionEntity, + List<String> identicalValuePropertyList) { + switch (unifiedCompositionEntity) { + case COMPUTE: + case OTHER: + Optional<String> identicalValueProperty = getIdenticalValuePropertyName(inputName, unifiedCompositionEntity); + return identicalValueProperty.filter(identicalValuePropertyList::contains).isPresent(); + case PORT: + return getPortPropertyNameFromInput(inputName, identicalValuePropertyList).isPresent(); + default: + return false; + } + } + + private Optional<String> getPortPropertyNameFromInput(String inputName, List<String> identicalValuePropertyList) { + for (String identicalProperty : identicalValuePropertyList) { + if (inputName.endsWith(identicalProperty)) { + return Optional.of(identicalProperty); + } + } return Optional.empty(); } - } - - private Object getPropertyValueFromNodeTemplate(String propertyName, NodeTemplate nodeTemplate) { - Map<String, Object> nodeTemplateProperties = nodeTemplate.getProperties(); - if (nodeTemplateProperties != null) { - Object propertyValue; - if (propertyName.startsWith(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME)) { - propertyValue = getServiceTemplateFilterPropertyValue(propertyName, nodeTemplateProperties); - } else { - propertyValue = nodeTemplateProperties.get(propertyName); - propertyValue = getClonedObject(propertyValue); - } - return propertyValue; - } - return null; - } - - private Object getServiceTemplateFilterPropertyValue(String propertyName, - Map<String, Object> nodeTemplateProperties) { - Object propertyValue = null; - Object serviceTemplateFilterProperties = - nodeTemplateProperties.get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); - String serviceTemplateFilterPropertyName = - propertyName.replace(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME + "_", ""); - - if (Objects.nonNull(serviceTemplateFilterProperties) - && serviceTemplateFilterProperties instanceof Map) { - propertyValue = ((Map<String, Object>) serviceTemplateFilterProperties).get(serviceTemplateFilterPropertyName); - } - return propertyValue; - } - - private Map<String, UnifiedCompositionEntity> getAllConsolidationNodeTemplateIdAndType( - List<UnifiedCompositionData> unifiedCompositionDataList) { - - Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType = new HashMap<>(); - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - if (Objects.nonNull(computeTemplateConsolidationData)) { - consolidationNodeTemplateIdAndType.put(computeTemplateConsolidationData.getNodeTemplateId(), COMPUTE); - } - List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - consolidationNodeTemplateIdAndType.put(subInterfaceTemplateConsolidationData.getNodeTemplateId(), - UnifiedCompositionEntity.SUB_INTERFACE); - } - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - consolidationNodeTemplateIdAndType.put(portTemplateConsolidationData.getNodeTemplateId(), - UnifiedCompositionEntity.PORT); - } - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - if (Objects.nonNull(nestedTemplateConsolidationData)) { - consolidationNodeTemplateIdAndType - .put(nestedTemplateConsolidationData.getNodeTemplateId(), - UnifiedCompositionEntity.NESTED); - } - } - return consolidationNodeTemplateIdAndType; - } - - private List<PortTemplateConsolidationData> getPortTemplateConsolidationDataList( - UnifiedCompositionData unifiedCompositionData) { - return unifiedCompositionData.getPortTemplateConsolidationDataList() == null ? new - ArrayList<>() : unifiedCompositionData.getPortTemplateConsolidationDataList(); - } - - private enum PropertyInputType { - NODE_TEMPLATE_ID, - TYPE, - OTHER - } + + private StringBuilder getPropertyValueStringBuilder(UnifiedCompositionEntity unifiedCompositionEntity) { + switch (unifiedCompositionEntity) { + case COMPUTE: + return getComputePropertyValueStringBuilder(); + case OTHER: + return getComputePropertyValueStringBuilder(); + case PORT: + return getPortPropertyValueStringBuilder(); + case SUB_INTERFACE: + return getSubInterfacePropertyValueStringBuilder(); + default: + return null; + } + } + + private StringBuilder getPortPropertyValueStringBuilder() { + StringBuilder builder; + builder = new StringBuilder(PORT_IDENTICAL_VALUE_PROPERTY_PREFIX); + builder.append(".+"); + return builder; + } + + private StringBuilder getComputePropertyValueStringBuilder() { + StringBuilder builder; + builder = new StringBuilder(COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX); + builder.append("[a-z]+"); + builder.append(COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX); + return builder; + } + + private StringBuilder getSubInterfacePropertyValueStringBuilder() { + StringBuilder builder; + builder = new StringBuilder(SUB_INTERFACE_PROPERTY_VALUE_PREFIX); + builder.append(".+"); + return builder; + } + + private Optional<String> getIdenticalValuePropertyName(String input, UnifiedCompositionEntity unifiedCompositionEntity) { + switch (unifiedCompositionEntity) { + case COMPUTE: + return Optional.of(input.split("_")[1]); + case OTHER: + return Optional.of(input.split("_")[1]); + case PORT: + return getPortPropertyNameFromInput(input, consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity)); + default: + return Optional.empty(); + } + } + + private Object getPropertyValueFromNodeTemplate(String propertyName, NodeTemplate nodeTemplate) { + Map<String, Object> nodeTemplateProperties = nodeTemplate.getProperties(); + if (nodeTemplateProperties != null) { + Object propertyValue; + if (propertyName.startsWith(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME)) { + propertyValue = getServiceTemplateFilterPropertyValue(propertyName, nodeTemplateProperties); + } else { + propertyValue = nodeTemplateProperties.get(propertyName); + propertyValue = getClonedObject(propertyValue); + } + return propertyValue; + } + return null; + } + + private Object getServiceTemplateFilterPropertyValue(String propertyName, Map<String, Object> nodeTemplateProperties) { + Object propertyValue = null; + Object serviceTemplateFilterProperties = nodeTemplateProperties.get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + String serviceTemplateFilterPropertyName = propertyName.replace(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME + "_", ""); + if (Objects.nonNull(serviceTemplateFilterProperties) && serviceTemplateFilterProperties instanceof Map) { + propertyValue = ((Map<String, Object>) serviceTemplateFilterProperties).get(serviceTemplateFilterPropertyName); + } + return propertyValue; + } + + private Map<String, UnifiedCompositionEntity> getAllConsolidationNodeTemplateIdAndType(List<UnifiedCompositionData> unifiedCompositionDataList) { + Map<String, UnifiedCompositionEntity> consolidationNodeTemplateIdAndType = new HashMap<>(); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + if (Objects.nonNull(computeTemplateConsolidationData)) { + consolidationNodeTemplateIdAndType.put(computeTemplateConsolidationData.getNodeTemplateId(), COMPUTE); + } + List<SubInterfaceTemplateConsolidationData> subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + consolidationNodeTemplateIdAndType + .put(subInterfaceTemplateConsolidationData.getNodeTemplateId(), UnifiedCompositionEntity.SUB_INTERFACE); + } + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + consolidationNodeTemplateIdAndType.put(portTemplateConsolidationData.getNodeTemplateId(), UnifiedCompositionEntity.PORT); + } + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.nonNull(nestedTemplateConsolidationData)) { + consolidationNodeTemplateIdAndType.put(nestedTemplateConsolidationData.getNodeTemplateId(), UnifiedCompositionEntity.NESTED); + } + } + return consolidationNodeTemplateIdAndType; + } + + private List<PortTemplateConsolidationData> getPortTemplateConsolidationDataList(UnifiedCompositionData unifiedCompositionData) { + return unifiedCompositionData.getPortTemplateConsolidationDataList() == null ? new ArrayList<>() + : unifiedCompositionData.getPortTemplateConsolidationDataList(); + } + + private enum PropertyInputType {NODE_TEMPLATE_ID, TYPE, OTHER} } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java index 82fb4b0c8e..00a3ff3ea4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java @@ -13,12 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -27,7 +25,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -44,178 +41,157 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida */ public class UnifiedCompositionUtil { - private UnifiedCompositionUtil() { - //Hiding the implicit public constructor - } - - /** - * Gets all ports per port type, which are connected to the computes from the input - * computeTemplateConsolidationDataCollection. - * - * @param computeTemplateConsolidationDataCollection collection of compute template - * consolidation data - * @return set of port ids, per port type - */ - static Map<String, List<String>> collectAllPortsFromEachTypesFromComputes( - Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationDataCollection) { - Map<String, List<String>> portTypeToIds = new HashMap<>(); - - for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDataCollection) { - Map<String, List<String>> ports = compute.getPorts(); - if (!MapUtils.isEmpty(ports)) { - addPortsToMap(portTypeToIds, ports); - } + private UnifiedCompositionUtil() { + //Hiding the implicit public constructor + } + + /** + * Gets all ports per port type, which are connected to the computes from the input computeTemplateConsolidationDataCollection. + * + * @param computeTemplateConsolidationDataCollection collection of compute template consolidation data + * @return set of port ids, per port type + */ + static Map<String, List<String>> collectAllPortsFromEachTypesFromComputes( + Collection<ComputeTemplateConsolidationData> computeTemplateConsolidationDataCollection) { + Map<String, List<String>> portTypeToIds = new HashMap<>(); + for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDataCollection) { + Map<String, List<String>> ports = compute.getPorts(); + if (!MapUtils.isEmpty(ports)) { + addPortsToMap(portTypeToIds, ports); + } + } + return portTypeToIds; + } + + static ListMultimap<String, SubInterfaceTemplateConsolidationData> collectAllSubInterfacesOfEachTypesFromPorts( + Collection<PortTemplateConsolidationData> portTemplateConsolidationDataCollection) { + ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceDataByType = ArrayListMultimap.create(); + for (PortTemplateConsolidationData port : portTemplateConsolidationDataCollection) { + port.copyMappedInto(subInterfaceDataByType); + } + return subInterfaceDataByType; + } + + private static void addPortsToMap(Map<String, List<String>> portTypeToIds, Map<String, List<String>> ports) { + for (Map.Entry<String, List<String>> portTypeToIdEntry : ports.entrySet()) { + portTypeToIds.putIfAbsent(portTypeToIdEntry.getKey(), new ArrayList<>()); + portTypeToIds.get(portTypeToIdEntry.getKey()).addAll(portTypeToIdEntry.getValue()); + } + } + + static String getComputeTypeSuffix(ServiceTemplate serviceTemplate, String computeNodeTemplateId) { + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); + if (Objects.nonNull(computeNodeTemplate)) { + return getComputeTypeSuffix(computeNodeTemplate.getType()); + } + return null; } - return portTypeToIds; - } + public static String getNewComputeNodeTemplateId(ServiceTemplate serviceTemplate, String computeNodeTemplateId) { + return getComputeTypeSuffix(serviceTemplate, computeNodeTemplateId); + } - static ListMultimap<String, SubInterfaceTemplateConsolidationData> - collectAllSubInterfacesOfEachTypesFromPorts(Collection<PortTemplateConsolidationData> - portTemplateConsolidationDataCollection) { - ListMultimap<String, SubInterfaceTemplateConsolidationData> subInterfaceDataByType = ArrayListMultimap.create(); - for (PortTemplateConsolidationData port : portTemplateConsolidationDataCollection) { - port.copyMappedInto(subInterfaceDataByType); + static String getComputeTypeSuffix(String computeType) { + return DataModelUtil.getNamespaceSuffix(computeType); } - return subInterfaceDataByType; - } - - private static void addPortsToMap(Map<String, List<String>> portTypeToIds, - Map<String, List<String>> ports) { - for (Map.Entry<String, List<String>> portTypeToIdEntry : ports.entrySet()) { - portTypeToIds.putIfAbsent(portTypeToIdEntry.getKey(), new ArrayList<>()); - portTypeToIds.get(portTypeToIdEntry.getKey()).addAll(portTypeToIdEntry.getValue()); + + public static ComputeTemplateConsolidationData getConnectedComputeConsolidationData(List<UnifiedCompositionData> unifiedCompositionDataList, + String portNodeTemplateId) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + if (Objects.isNull(unifiedCompositionData.getComputeTemplateConsolidationData().getPorts())) { + continue; + } + Collection<List<String>> portsCollection = unifiedCompositionData.getComputeTemplateConsolidationData().getPorts().values(); + for (List<String> portIdList : portsCollection) { + if (portIdList.contains(portNodeTemplateId)) { + return unifiedCompositionData.getComputeTemplateConsolidationData(); + } + } + } + return null; } - } - static String getComputeTypeSuffix(ServiceTemplate serviceTemplate, - String computeNodeTemplateId) { - NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); - if (Objects.nonNull(computeNodeTemplate)) { - return getComputeTypeSuffix(computeNodeTemplate.getType()); + public static PortTemplateConsolidationData getPortTemplateConsolidationDataForPort(List<UnifiedCompositionData> unifiedCompositionDataList, + String portNodeTemplateId) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + if (CollectionUtils.isEmpty(unifiedCompositionData.getPortTemplateConsolidationDataList())) { + continue; + } + List<PortTemplateConsolidationData> portTemplateConsolidationDataList = unifiedCompositionData.getPortTemplateConsolidationDataList(); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + if (portTemplateConsolidationData.getNodeTemplateId().equals(portNodeTemplateId)) { + return portTemplateConsolidationData; + } + } + } + return null; } - return null; - } - - public static String getNewComputeNodeTemplateId(ServiceTemplate serviceTemplate, String computeNodeTemplateId) { - return getComputeTypeSuffix(serviceTemplate, computeNodeTemplateId); - } - - static String getComputeTypeSuffix(String computeType) { - return DataModelUtil.getNamespaceSuffix(computeType); - } - - public static ComputeTemplateConsolidationData getConnectedComputeConsolidationData( - List<UnifiedCompositionData> unifiedCompositionDataList, - String portNodeTemplateId) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - if (Objects.isNull(unifiedCompositionData.getComputeTemplateConsolidationData().getPorts())) { - continue; - } - Collection<List<String>> portsCollection = - unifiedCompositionData.getComputeTemplateConsolidationData().getPorts().values(); - for (List<String> portIdList : portsCollection) { - if (portIdList.contains(portNodeTemplateId)) { - return unifiedCompositionData.getComputeTemplateConsolidationData(); + + //The ID should be <vm_type>_<port_type> or <vm_type>_<portNodeTemplateId> + public static String getNewPortNodeTemplateId(String portNodeTemplateId, String connectedComputeNodeType, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + StringBuilder newPortNodeTemplateId = new StringBuilder(); + String portType = ConsolidationDataUtil.getPortType(portNodeTemplateId, DataModelUtil.getNamespaceSuffix(connectedComputeNodeType)); + newPortNodeTemplateId.append(DataModelUtil.getNamespaceSuffix(connectedComputeNodeType)); + if (computeTemplateConsolidationData.getPorts().get(portType) != null + && computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { + //single port + newPortNodeTemplateId.append("_").append(portNodeTemplateId); + } else { + //consolidation port + newPortNodeTemplateId.append("_").append(portType); } - } + return newPortNodeTemplateId.toString(); } - return null; - } - - public static PortTemplateConsolidationData getPortTemplateConsolidationDataForPort(List<UnifiedCompositionData> - unifiedCompositionDataList, - String portNodeTemplateId) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - if (CollectionUtils.isEmpty(unifiedCompositionData.getPortTemplateConsolidationDataList())) { - continue; - } - List<PortTemplateConsolidationData> portTemplateConsolidationDataList = - unifiedCompositionData.getPortTemplateConsolidationDataList(); - for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { - if (portTemplateConsolidationData.getNodeTemplateId().equals(portNodeTemplateId)) { - return portTemplateConsolidationData; + + public static String getNewSubInterfaceNodeTemplateId(ServiceTemplate serviceTemplate, String connectedComputeNodeType, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData, + TranslationContext context) { + //The ID should be <vm_type>_<portType/NodetemplateId>_<subInterface_type> + + // or <vm_type>_<portType/NodetemplateId>_<subInterfaceNodeTemplateId> + StringBuilder newSubInterfaceNodeTemplateId = new StringBuilder(); + newSubInterfaceNodeTemplateId.append( + getNewPortNodeTemplateId(subInterfaceTemplateConsolidationData.getParentPortNodeTemplateId(), connectedComputeNodeType, + computeTemplateConsolidationData)); + Optional<PortTemplateConsolidationData> portTemplateConsolidationData = subInterfaceTemplateConsolidationData + .getParentPortTemplateConsolidationData(serviceTemplate, context); + NodeTemplate subInterfaceNodeTemplate = DataModelUtil + .getNodeTemplate(serviceTemplate, subInterfaceTemplateConsolidationData.getNodeTemplateId()); + if (portTemplateConsolidationData.isPresent()) { + String subInterfaceSuffix = getSubInterfaceSuffix(portTemplateConsolidationData.get(), subInterfaceNodeTemplate, + subInterfaceTemplateConsolidationData); + newSubInterfaceNodeTemplateId.append("_").append(subInterfaceSuffix); + return newSubInterfaceNodeTemplateId.toString(); } - } + return subInterfaceTemplateConsolidationData.getNodeTemplateId(); } - return null; - } - - //The ID should be <vm_type>_<port_type> or <vm_type>_<portNodeTemplateId> - public static String getNewPortNodeTemplateId( - String portNodeTemplateId, - String connectedComputeNodeType, - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - - StringBuilder newPortNodeTemplateId = new StringBuilder(); - String portType = ConsolidationDataUtil.getPortType(portNodeTemplateId, - DataModelUtil.getNamespaceSuffix(connectedComputeNodeType)); - newPortNodeTemplateId.append(DataModelUtil.getNamespaceSuffix(connectedComputeNodeType)); - if (computeTemplateConsolidationData.getPorts().get(portType) != null - && computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { - //single port - newPortNodeTemplateId.append("_").append(portNodeTemplateId); - } else { - //consolidation port - newPortNodeTemplateId.append("_").append(portType); + + static String getSubInterfaceTypeSuffix(String nodeType) { + return DataModelUtil.getNamespaceSuffix(nodeType); } - return newPortNodeTemplateId.toString(); - } - - public static String getNewSubInterfaceNodeTemplateId(ServiceTemplate serviceTemplate, - String connectedComputeNodeType, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - SubInterfaceTemplateConsolidationData - subInterfaceTemplateConsolidationData, - TranslationContext context) { - //The ID should be <vm_type>_<portType/NodetemplateId>_<subInterface_type> - // or <vm_type>_<portType/NodetemplateId>_<subInterfaceNodeTemplateId> - StringBuilder newSubInterfaceNodeTemplateId = new StringBuilder(); - newSubInterfaceNodeTemplateId.append(getNewPortNodeTemplateId(subInterfaceTemplateConsolidationData - .getParentPortNodeTemplateId(), connectedComputeNodeType, computeTemplateConsolidationData)); - Optional<PortTemplateConsolidationData> portTemplateConsolidationData = - subInterfaceTemplateConsolidationData.getParentPortTemplateConsolidationData(serviceTemplate, context); - NodeTemplate subInterfaceNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, subInterfaceTemplateConsolidationData.getNodeTemplateId()); - if (portTemplateConsolidationData.isPresent()) { - String subInterfaceSuffix = getSubInterfaceSuffix(portTemplateConsolidationData.get(), - subInterfaceNodeTemplate, subInterfaceTemplateConsolidationData); - newSubInterfaceNodeTemplateId.append("_").append(subInterfaceSuffix); - return newSubInterfaceNodeTemplateId.toString(); + + public static List<SubInterfaceTemplateConsolidationData> getSubInterfaceTemplateConsolidationDataList( + UnifiedCompositionData unifiedCompositionData) { + return unifiedCompositionData.getSubInterfaceTemplateConsolidationDataList() == null ? Collections.emptyList() + : unifiedCompositionData.getSubInterfaceTemplateConsolidationDataList(); } - return subInterfaceTemplateConsolidationData.getNodeTemplateId(); - } - - static String getSubInterfaceTypeSuffix(String nodeType) { - return DataModelUtil.getNamespaceSuffix(nodeType); - } - - public static List<SubInterfaceTemplateConsolidationData> getSubInterfaceTemplateConsolidationDataList( - UnifiedCompositionData unifiedCompositionData) { - return unifiedCompositionData.getSubInterfaceTemplateConsolidationDataList() == null ? Collections.emptyList() : - unifiedCompositionData.getSubInterfaceTemplateConsolidationDataList(); - } - - private static String getSubInterfaceSuffix(PortTemplateConsolidationData portTemplateConsolidationData, - NodeTemplate subInterfaceNodeTemplate, - SubInterfaceTemplateConsolidationData - subInterfaceTemplateConsolidationData) { - if (portTemplateConsolidationData.isSubInterfaceNodeTemplateIdParameter(subInterfaceNodeTemplate.getType())) { - //If there are more than one subinterfaces with same type use node template id - return subInterfaceTemplateConsolidationData.getNodeTemplateId(); + + private static String getSubInterfaceSuffix(PortTemplateConsolidationData portTemplateConsolidationData, NodeTemplate subInterfaceNodeTemplate, + SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData) { + if (portTemplateConsolidationData.isSubInterfaceNodeTemplateIdParameter(subInterfaceNodeTemplate.getType())) { + //If there are more than one subinterfaces with same type use node template id + return subInterfaceTemplateConsolidationData.getNodeTemplateId(); + } + //Add sub interface type since we have only one subinterface per type + return getSubInterfaceTypeSuffix(subInterfaceNodeTemplate.getType()); } - //Add sub interface type since we have only one subinterface per type - return getSubInterfaceTypeSuffix(subInterfaceNodeTemplate.getType()); - } - public static Map<String, List<String>> collectAllPortsOfEachTypeFromComputes( - List<UnifiedCompositionData> unifiedCompositionDataList) { + public static Map<String, List<String>> collectAllPortsOfEachTypeFromComputes(List<UnifiedCompositionData> unifiedCompositionDataList) { Map<String, List<String>> portIdsPerPortType = new HashMap<>(); - unifiedCompositionDataList - .forEach(unifiedCompositionData -> - unifiedCompositionData.getComputeTemplateConsolidationData() - .collectAllPortsOfEachTypeFromCompute(portIdsPerPortType)); - + unifiedCompositionDataList.forEach(unifiedCompositionData -> unifiedCompositionData.getComputeTemplateConsolidationData() + .collectAllPortsOfEachTypeFromCompute(portIdsPerPortType)); return portIdsPerPortType; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java index 9fa086eb17..3bc540d9ae 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java @@ -24,12 +24,10 @@ import org.openecomp.sdc.common.errors.ErrorCategory; public final class DuplicateResourceIdsInDifferentFilesErrorBuilder extends BaseErrorBuilder { - private static final String DUPLICATE_RESOURCE_ID_MSG = "Resource with id %s occurs more than once in " + - "different addOn files"; + private static final String DUPLICATE_RESOURCE_ID_MSG = "Resource with id %s occurs more than once in " + "different addOn files"; - public DuplicateResourceIdsInDifferentFilesErrorBuilder(String resourceId) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES) - .withCategory(ErrorCategory.APPLICATION) - .withMessage(String.format(DUPLICATE_RESOURCE_ID_MSG, resourceId)); - } + public DuplicateResourceIdsInDifferentFilesErrorBuilder(String resourceId) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES).withCategory(ErrorCategory.APPLICATION) + .withMessage(String.format(DUPLICATE_RESOURCE_ID_MSG, resourceId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java index fddf2a82d8..81f5860801 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,36 +17,32 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class IncorrectResourceReferenceErrorBuilder extends BaseErrorBuilder { - private static final String INCORRECT_RESOURCE_REFERENCE_MSG = - "resource id '%s' with type '%s' has reference to resource '%s' with" - + " type '%s' in property '%s'. Invalid type, resource type should be type of '%s'."; + private static final String INCORRECT_RESOURCE_REFERENCE_MSG = "resource id '%s' with type '%s' has reference to resource '%s' with" + + " type '%s' in property '%s'. Invalid type, resource type should be type of '%s'."; - /** - * Instantiates a new Incorrect resource reference error builder. - * - * @param sourceResourceId the source resource id - * @param sourceResourceType the source resource type - * @param targetResourceId the target resource id - * @param targetResourceType the target resource type - * @param property the property - * @param validType the valid type - */ - public IncorrectResourceReferenceErrorBuilder(String sourceResourceId, String sourceResourceType, - String targetResourceId, String targetResourceType, - String property, String validType) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.INCORRECT_RESOURCE_REFERENCE); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String - .format(INCORRECT_RESOURCE_REFERENCE_MSG, sourceResourceId, sourceResourceType, - targetResourceId, targetResourceType, property, validType)); - } + /** + * Instantiates a new Incorrect resource reference error builder. + * + * @param sourceResourceId the source resource id + * @param sourceResourceType the source resource type + * @param targetResourceId the target resource id + * @param targetResourceType the target resource type + * @param property the property + * @param validType the valid type + */ + public IncorrectResourceReferenceErrorBuilder(String sourceResourceId, String sourceResourceType, String targetResourceId, + String targetResourceType, String property, String validType) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.INCORRECT_RESOURCE_REFERENCE); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String + .format(INCORRECT_RESOURCE_REFERENCE_MSG, sourceResourceId, sourceResourceType, targetResourceId, targetResourceType, property, + validType)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/InvalidPropertyValueErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/InvalidPropertyValueErrorBuilder.java index a16c341545..ee533fa6cb 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/InvalidPropertyValueErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/InvalidPropertyValueErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,31 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class InvalidPropertyValueErrorBuilder extends BaseErrorBuilder { - private static final String INVALID_FILED_VALUE_MSG = - "'%s' property has invalid value. Actual value is '%s' while '%s' value expected."; - - /** - * Instantiates a new Invalid property value error builder. - * - * @param propertyName the property name - * @param actualValue the actual value - * @param expectedValue the expected value - */ - public InvalidPropertyValueErrorBuilder(String propertyName, String actualValue, - String expectedValue) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.INVALID_PROPERTY_VALUE); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage( - String.format(INVALID_FILED_VALUE_MSG, propertyName, actualValue, expectedValue)); - } + private static final String INVALID_FILED_VALUE_MSG = "'%s' property has invalid value. Actual value is '%s' while '%s' value expected."; + /** + * Instantiates a new Invalid property value error builder. + * + * @param propertyName the property name + * @param actualValue the actual value + * @param expectedValue the expected value + */ + public InvalidPropertyValueErrorBuilder(String propertyName, String actualValue, String expectedValue) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.INVALID_PROPERTY_VALUE); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(INVALID_FILED_VALUE_MSG, propertyName, actualValue, expectedValue)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/MissingMandatoryPropertyErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/MissingMandatoryPropertyErrorBuilder.java index 6e06fef930..2232575cca 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/MissingMandatoryPropertyErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/MissingMandatoryPropertyErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,27 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class MissingMandatoryPropertyErrorBuilder extends BaseErrorBuilder { - private static final String MANDATORY_PROPERTY_IS_MISSING_MSG = - "Mandatory property '%s' is missing"; + private static final String MANDATORY_PROPERTY_IS_MISSING_MSG = "Mandatory property '%s' is missing"; - /** - * Instantiates a new Missing mandatory property error builder. - * - * @param propertyName the property name - */ - public MissingMandatoryPropertyErrorBuilder(String propertyName) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.MISSING_MANDATORY_PROPERTY); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder() - .withMessage(String.format(MANDATORY_PROPERTY_IS_MISSING_MSG, propertyName)); - } + /** + * Instantiates a new Missing mandatory property error builder. + * + * @param propertyName the property name + */ + public MissingMandatoryPropertyErrorBuilder(String propertyName) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.MISSING_MANDATORY_PROPERTY); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(MANDATORY_PROPERTY_IS_MISSING_MSG, propertyName)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java index ae903946e4..de944ce856 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class NotInSyncNumberOfInterfacesErrorBuilder extends BaseErrorBuilder { - private static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES_MSG = - "More than one ServiceInstance pointing to the same " - + "ServiceTemplate '%s', with different number of interfaces."; + private static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES_MSG = + "More than one ServiceInstance pointing to the same " + "ServiceTemplate '%s', with different number of interfaces."; - /** - * Instantiates a new Not in sync number of interfaces error builder. - * - * @param serviceTemplateResourceId the service template resource id - */ - public NotInSyncNumberOfInterfacesErrorBuilder(String serviceTemplateResourceId) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.NOT_IN_SYNC_NUMBER_OF_INTERFACES); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage( - String.format(NOT_IN_SYNC_NUMBER_OF_INTERFACES_MSG, serviceTemplateResourceId)); - } + /** + * Instantiates a new Not in sync number of interfaces error builder. + * + * @param serviceTemplateResourceId the service template resource id + */ + public NotInSyncNumberOfInterfacesErrorBuilder(String serviceTemplateResourceId) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.NOT_IN_SYNC_NUMBER_OF_INTERFACES); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(NOT_IN_SYNC_NUMBER_OF_INTERFACES_MSG, serviceTemplateResourceId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java index dc41e5d207..73b511b227 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,36 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class ReferenceToUnsupportedResourceErrorBuilder extends BaseErrorBuilder { - private static final String REFERENCE_TO_UNSUPPORTED_RESOURCE_MSG = - "Resource id '%s' with type '%s' has reference " - + "to unsupported resource '%s' with type '%s' in property '%s'"; + private static final String REFERENCE_TO_UNSUPPORTED_RESOURCE_MSG = + "Resource id '%s' with type '%s' has reference " + "to unsupported resource '%s' with type '%s' in property '%s'"; - /** - * Instantiates a new Reference to unsupported resource error builder. - * - * @param sourceResourceId the source resource id - * @param sourceResourceType the source resource type - * @param targetResourceId the target resource id - * @param targetResourceType the target resource type - * @param property the property - */ - public ReferenceToUnsupportedResourceErrorBuilder(String sourceResourceId, - String sourceResourceType, - String targetResourceId, - String targetResourceType, String property) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.REFERENCE_TO_UNSUPPORTED_RESOURCE); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String - .format(REFERENCE_TO_UNSUPPORTED_RESOURCE_MSG, sourceResourceId, sourceResourceType, - targetResourceId, targetResourceType, property)); - } + /** + * Instantiates a new Reference to unsupported resource error builder. + * + * @param sourceResourceId the source resource id + * @param sourceResourceType the source resource type + * @param targetResourceId the target resource id + * @param targetResourceType the target resource type + * @param property the property + */ + public ReferenceToUnsupportedResourceErrorBuilder(String sourceResourceId, String sourceResourceType, String targetResourceId, + String targetResourceType, String property) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.REFERENCE_TO_UNSUPPORTED_RESOURCE); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String + .format(REFERENCE_TO_UNSUPPORTED_RESOURCE_MSG, sourceResourceId, sourceResourceType, targetResourceId, targetResourceType, property)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ResourceNotFoundInHeatFileErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ResourceNotFoundInHeatFileErrorBuilder.java index 7fac501e76..506a0d92f4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ResourceNotFoundInHeatFileErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ResourceNotFoundInHeatFileErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,28 +24,23 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class ResourceNotFoundInHeatFileErrorBuilder { - private static final String RESOURCE_NOT_FOUND_IN_FILE_ERR_ID = - "RESOURCE_NOT_FOUND_IN_FILE_ERR_ID"; - private static final String RESOURCE_NOT_FOUND_IN_FILE_ERR_MSG = - "resource with id = %s was not found in heat file = %s."; - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Instantiates a new Resource not found in heat file error builder. - * - * @param resourceId the resource id - * @param heatfileName the heatfile name - */ - public ResourceNotFoundInHeatFileErrorBuilder(String resourceId, String heatfileName) { - builder.withId(RESOURCE_NOT_FOUND_IN_FILE_ERR_ID); - builder.withCategory(ErrorCategory.APPLICATION); - builder - .withMessage(String.format(RESOURCE_NOT_FOUND_IN_FILE_ERR_MSG, resourceId, heatfileName)); - } - - public ErrorCode build() { - return builder.build(); - } - + private static final String RESOURCE_NOT_FOUND_IN_FILE_ERR_ID = "RESOURCE_NOT_FOUND_IN_FILE_ERR_ID"; + private static final String RESOURCE_NOT_FOUND_IN_FILE_ERR_MSG = "resource with id = %s was not found in heat file = %s."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Resource not found in heat file error builder. + * + * @param resourceId the resource id + * @param heatfileName the heatfile name + */ + public ResourceNotFoundInHeatFileErrorBuilder(String resourceId, String heatfileName) { + builder.withId(RESOURCE_NOT_FOUND_IN_FILE_ERR_ID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(RESOURCE_NOT_FOUND_IN_FILE_ERR_MSG, resourceId, heatfileName)); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java index 5afb1ae3c2..0a03847da2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; - public class TranslatorErrorCodes { - public static final String MISSING_MANDATORY_PROPERTY = "MISSING_MANDATORY_PROPERTY"; - public static final String HEAT_TO_TOSCA_MAPPING_COLLISION = "HEAT_TO_TOSCA_MAPPING_COLLISION"; - public static final String INCORRECT_RESOURCE_REFERENCE = "INCORRECT_RESOURCE_REFERENCE"; - public static final String REFERENCE_TO_UNSUPPORTED_RESOURCE = - "REFERENCE_TO_UNSUPPORTED_RESOURCE"; - public static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES = "NOT_IN_SYNC_NUMBER_OF_INTERFACES"; - public static final String INVALID_PROPERTY_VALUE = "INVALID_PROPERTY_VALUE"; - public static final String DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES = "DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES"; + + public static final String MISSING_MANDATORY_PROPERTY = "MISSING_MANDATORY_PROPERTY"; + public static final String HEAT_TO_TOSCA_MAPPING_COLLISION = "HEAT_TO_TOSCA_MAPPING_COLLISION"; + public static final String INCORRECT_RESOURCE_REFERENCE = "INCORRECT_RESOURCE_REFERENCE"; + public static final String REFERENCE_TO_UNSUPPORTED_RESOURCE = "REFERENCE_TO_UNSUPPORTED_RESOURCE"; + public static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES = "NOT_IN_SYNC_NUMBER_OF_INTERFACES"; + public static final String INVALID_PROPERTY_VALUE = "INVALID_PROPERTY_VALUE"; + public static final String DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES = "DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES"; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java index 5a3dc7e042..0031d209e0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java @@ -13,66 +13,57 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.globaltypes; -import org.onap.sdc.tosca.datatypes.model.Import; -import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - +import org.onap.sdc.tosca.datatypes.model.Import; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; public class GlobalTypesGenerator { - private GlobalTypesGenerator() { - } + private GlobalTypesGenerator() { + } - /** - * Gets global types service template. - * - * @return the global types service template - */ - public static Map<String, ServiceTemplate> getGlobalTypesServiceTemplate(OnboardingTypesEnum - onboardingType) { - return GlobalTypesServiceTemplates.getGlobalTypesServiceTemplates(onboardingType); - } + /** + * Gets global types service template. + * + * @return the global types service template + */ + public static Map<String, ServiceTemplate> getGlobalTypesServiceTemplate(OnboardingTypesEnum onboardingType) { + return GlobalTypesServiceTemplates.getGlobalTypesServiceTemplates(onboardingType); + } - /** - * Gets global types import list. - * - * @return the global types import list - */ - public static List<Map<String, Import>> getGlobalTypesImportList() { - List<Map<String, Import>> globalImports = new ArrayList<>(); - Map<String, Import> globalImportMap = new HashMap<>(); - Map<String, ServiceTemplate> globalTypesServiceTemplate = - GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP); - globalImportMap.put("openecomp_heat_index", - HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get - ("openecomp-heat/_index.yml"))); - globalImports.add(globalImportMap); - return globalImports; - } + /** + * Gets global types import list. + * + * @return the global types import list + */ + public static List<Map<String, Import>> getGlobalTypesImportList() { + List<Map<String, Import>> globalImports = new ArrayList<>(); + Map<String, Import> globalImportMap = new HashMap<>(); + Map<String, ServiceTemplate> globalTypesServiceTemplate = GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP); + globalImportMap + .put("openecomp_heat_index", HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get("openecomp-heat/_index.yml"))); + globalImports.add(globalImportMap); + return globalImports; + } - /** - * Gets global types import list for Manual Vsp onboarding. - * - * @return the global types import list - */ - public static List<Map<String, Import>> getManualVspGlobalTypesImportList() { - List<Map<String, Import>> globalImports = new ArrayList<>(); - Map<String, Import> globalImportMap = new HashMap<>(); - Map<String, ServiceTemplate> globalTypesServiceTemplate = - GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.MANUAL); - globalImportMap.put("openecomp_index", - HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get - ("openecomp/_index.yml"))); - globalImports.add(globalImportMap); - return globalImports; - } + /** + * Gets global types import list for Manual Vsp onboarding. + * + * @return the global types import list + */ + public static List<Map<String, Import>> getManualVspGlobalTypesImportList() { + List<Map<String, Import>> globalImports = new ArrayList<>(); + Map<String, Import> globalImportMap = new HashMap<>(); + Map<String, ServiceTemplate> globalTypesServiceTemplate = GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.MANUAL); + globalImportMap.put("openecomp_index", HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get("openecomp/_index.yml"))); + globalImports.add(globalImportMap); + return globalImports; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java index dc63f970cd..2c6516eca9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.globaltypes; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; @@ -26,18 +28,11 @@ import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.utils.ResourceWalker; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - public class GlobalTypesServiceTemplates { private static final String ONAP_FILEPATH_REGEX = ".*" + Constants.GLOBAL_TYPES + "(/onap/|\\\\onap\\\\).*"; private static final Map<OnboardingTypesEnum, Map<String, ServiceTemplate>> onboardingGlobalTypesServiceTemplates; - private GlobalTypesServiceTemplates() { - } - static { Map<String, String> globalTypes; try { @@ -45,35 +40,31 @@ public class GlobalTypesServiceTemplates { } catch (CoreException coreException) { throw coreException; } catch (Exception exception) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Constants.FAILED_TO_GENERATE_GLOBAL_TYPES) - .withId(Constants.GLOBAL_TYPES_READ_ERROR) - .withCategory(ErrorCategory.APPLICATION).build(), exception); + throw new CoreException( + (new ErrorCode.ErrorCodeBuilder()).withMessage(Constants.FAILED_TO_GENERATE_GLOBAL_TYPES).withId(Constants.GLOBAL_TYPES_READ_ERROR) + .withCategory(ErrorCategory.APPLICATION).build(), exception); } onboardingGlobalTypesServiceTemplates = init(globalTypes); } + private GlobalTypesServiceTemplates() { + } + public static Map<String, ServiceTemplate> getGlobalTypesServiceTemplates(OnboardingTypesEnum onboardingType) { if (onboardingType == null) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Constants.FAILED_TO_GENERATE_GLOBAL_TYPES) - .withId(Constants.INVALID_ONBOARDING_TYPE) - .withCategory(ErrorCategory.APPLICATION).build()); + throw new CoreException( + (new ErrorCode.ErrorCodeBuilder()).withMessage(Constants.FAILED_TO_GENERATE_GLOBAL_TYPES).withId(Constants.INVALID_ONBOARDING_TYPE) + .withCategory(ErrorCategory.APPLICATION).build()); } return onboardingGlobalTypesServiceTemplates.get(onboardingType); } private static Map<OnboardingTypesEnum, Map<String, ServiceTemplate>> init(Map<String, String> globalTypes) { - Map<OnboardingTypesEnum, Map<String, ServiceTemplate>> onboardingGlobalTypesServiceTemplates = - new EnumMap<>(OnboardingTypesEnum.class); - Map<String, ServiceTemplate> zipOnboardingGlobalTypes = - getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.ZIP); - Map<String, ServiceTemplate> csarOnboardingGlobalTypes = - getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.CSAR); - Map<String, ServiceTemplate> manualOnboardingGlobalTypes = - getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.MANUAL); - Map<String, ServiceTemplate> defaultOnboardingGlobalTypes = - getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.NONE); + Map<OnboardingTypesEnum, Map<String, ServiceTemplate>> onboardingGlobalTypesServiceTemplates = new EnumMap<>(OnboardingTypesEnum.class); + Map<String, ServiceTemplate> zipOnboardingGlobalTypes = getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.ZIP); + Map<String, ServiceTemplate> csarOnboardingGlobalTypes = getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.CSAR); + Map<String, ServiceTemplate> manualOnboardingGlobalTypes = getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.MANUAL); + Map<String, ServiceTemplate> defaultOnboardingGlobalTypes = getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.NONE); onboardingGlobalTypesServiceTemplates.put(OnboardingTypesEnum.ZIP, zipOnboardingGlobalTypes); onboardingGlobalTypesServiceTemplates.put(OnboardingTypesEnum.CSAR, csarOnboardingGlobalTypes); onboardingGlobalTypesServiceTemplates.put(OnboardingTypesEnum.MANUAL, manualOnboardingGlobalTypes); @@ -81,8 +72,7 @@ public class GlobalTypesServiceTemplates { return onboardingGlobalTypesServiceTemplates; } - private static Map<String, ServiceTemplate> getOnboardingGlobalTypes(Map<String, String> globalTypes, - OnboardingTypesEnum onboardingType) { + private static Map<String, ServiceTemplate> getOnboardingGlobalTypes(Map<String, String> globalTypes, OnboardingTypesEnum onboardingType) { Map<String, ServiceTemplate> globalTypesServiceTemplates = new HashMap<>(); ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); for (Map.Entry<String, String> globalTypeContent : globalTypes.entrySet()) { @@ -91,13 +81,12 @@ public class GlobalTypesServiceTemplates { continue; } ToscaUtil.addServiceTemplateToMapWithKeyFileName(globalTypesServiceTemplates, - toscaExtensionYamlUtil.yamlToObject(globalTypeContent.getValue(), ServiceTemplate.class)); + toscaExtensionYamlUtil.yamlToObject(globalTypeContent.getValue(), ServiceTemplate.class)); } return globalTypesServiceTemplates; } - private static boolean isTypeValidCandidateForCsarPacking(String globalTypeResourceKey, - OnboardingTypesEnum onboardingType) { + private static boolean isTypeValidCandidateForCsarPacking(String globalTypeResourceKey, OnboardingTypesEnum onboardingType) { if (globalTypeResourceKey.contains(Constants.OPENECOMP_INVENTORY)) { // this global types folders should not be processed to the CSAR return false; @@ -105,5 +94,4 @@ public class GlobalTypesServiceTemplates { //Global types specific to csar onboarding should not be packed for other onboarding types return !globalTypeResourceKey.matches(ONAP_FILEPATH_REGEX) || onboardingType == OnboardingTypesEnum.CSAR; } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java index cabb92c254..c36d8c66fa 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.helper; import java.util.ArrayList; @@ -26,7 +25,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; - import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.heat.datatypes.HeatBoolean; import org.openecomp.sdc.heat.datatypes.model.Resource; @@ -37,108 +35,89 @@ import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; public class ContrailTranslationHelper { - /** - * Gets compute node type id. - * - * @param contrailServiceTemplateResource contrail service teamplte resource - * @param contrailServiceTemplateResourceId contrailservice template resource id - * @param contrailServiceTemplateTranslatedId contrail service tempalte resource translated id - * @return the compute node type id - */ - public String getComputeNodeTypeId(Resource contrailServiceTemplateResource, - String contrailServiceTemplateResourceId, - String contrailServiceTemplateTranslatedId, - TranslationContext context) { - NameExtractor nodeTypeNameExtractor = - context.getNameExtractorImpl(ConfigConstants.CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY); - return nodeTypeNameExtractor - .extractNodeTypeName(contrailServiceTemplateResource, contrailServiceTemplateResourceId, - contrailServiceTemplateTranslatedId); - } - - /** - * Get property Regx matcher list. - * - * @return Regex exprission per contrail service template resource property, while contail compute - * type name is consider when setting the name value - */ - public List<PropertyRegexMatcher> getPropertyRegexMatchersForComputeNodeType() { - List<PropertyRegexMatcher> propertyRegexMatchers = new ArrayList<>(); - propertyRegexMatchers - .add(new PropertyRegexMatcher("image_name", Collections.singletonList(".+_image_name$"), - "_image_name")); - propertyRegexMatchers - .add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), - "_flavor_name")); - return propertyRegexMatchers; - } - public String getSubstitutionContrailServiceTemplateMetadata(String heatFileName, - String serviceInstanceTranslatedId) { - return FileUtils.getFileWithoutExtention(heatFileName) + "_" + serviceInstanceTranslatedId; - } - - /** - * Translate fn split function optional. - * - * @param propertyValue the property value - * @param listSize the list size - * @param includeBooleanValue the include boolean value - * @return the optional - */ - public Optional<List<Map<String, List>>> translateFnSplitFunction(Object propertyValue, - int listSize, - boolean - includeBooleanValue) { - List<Map<String, List>> tokenPropertyValueList = new ArrayList<>(); - - if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { - Map<String, Object> propMap = (Map) propertyValue; - Map.Entry<String, Object> entry = propMap.entrySet().iterator().next(); - Object entity = entry.getValue(); - String key = entry.getKey(); - String tokenChar; + /** + * Gets compute node type id. + * + * @param contrailServiceTemplateResource contrail service teamplte resource + * @param contrailServiceTemplateResourceId contrailservice template resource id + * @param contrailServiceTemplateTranslatedId contrail service tempalte resource translated id + * @return the compute node type id + */ + public String getComputeNodeTypeId(Resource contrailServiceTemplateResource, String contrailServiceTemplateResourceId, + String contrailServiceTemplateTranslatedId, TranslationContext context) { + NameExtractor nodeTypeNameExtractor = context.getNameExtractorImpl(ConfigConstants.CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY); + return nodeTypeNameExtractor + .extractNodeTypeName(contrailServiceTemplateResource, contrailServiceTemplateResourceId, contrailServiceTemplateTranslatedId); + } - if (key.equals("Fn::Split") && entity instanceof List) { - tokenChar = (String) ((List) entity).get(0); - Object refParameter = ((List) entity).get(1); + /** + * Get property Regx matcher list. + * + * @return Regex exprission per contrail service template resource property, while contail compute type name is consider when setting the name + * value + */ + public List<PropertyRegexMatcher> getPropertyRegexMatchersForComputeNodeType() { + List<PropertyRegexMatcher> propertyRegexMatchers = new ArrayList<>(); + propertyRegexMatchers.add(new PropertyRegexMatcher("image_name", Collections.singletonList(".+_image_name$"), "_image_name")); + propertyRegexMatchers.add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), "_flavor_name")); + return propertyRegexMatchers; + } - for (int substringIndex = 0; substringIndex < listSize; substringIndex++) { - Map<String, List> tokenPropertyValue = new HashMap<>(); - tokenPropertyValue.put("token", new ArrayList<>()); + public String getSubstitutionContrailServiceTemplateMetadata(String heatFileName, String serviceInstanceTranslatedId) { + return FileUtils.getFileWithoutExtention(heatFileName) + "_" + serviceInstanceTranslatedId; + } - if (refParameter instanceof Map && ((Map) refParameter).get("Ref") != null) { - Map<String, String> stringWithToken = new HashMap<>(); - ((Map) stringWithToken) - .put(ToscaFunctions.GET_INPUT.getFunctionName(), ((Map) refParameter).get("Ref")); - tokenPropertyValue.get("token").add(stringWithToken); - } else if (refParameter instanceof String) { - if (includeBooleanValue) { - StringBuilder booleanBuilder = new StringBuilder(); - String[] booleanValueList = ((String) refParameter).split(tokenChar); - for (int i = 0; i < booleanValueList.length; i++) { - if (i == 0) { - booleanBuilder.append(HeatBoolean.eval(booleanValueList[i])); - } else { - booleanBuilder.append(tokenChar); - booleanBuilder.append(HeatBoolean.eval(booleanValueList[i])); + /** + * Translate fn split function optional. + * + * @param propertyValue the property value + * @param listSize the list size + * @param includeBooleanValue the include boolean value + * @return the optional + */ + public Optional<List<Map<String, List>>> translateFnSplitFunction(Object propertyValue, int listSize, boolean includeBooleanValue) { + List<Map<String, List>> tokenPropertyValueList = new ArrayList<>(); + if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { + Map<String, Object> propMap = (Map) propertyValue; + Map.Entry<String, Object> entry = propMap.entrySet().iterator().next(); + Object entity = entry.getValue(); + String key = entry.getKey(); + String tokenChar; + if (key.equals("Fn::Split") && entity instanceof List) { + tokenChar = (String) ((List) entity).get(0); + Object refParameter = ((List) entity).get(1); + for (int substringIndex = 0; substringIndex < listSize; substringIndex++) { + Map<String, List> tokenPropertyValue = new HashMap<>(); + tokenPropertyValue.put("token", new ArrayList<>()); + if (refParameter instanceof Map && ((Map) refParameter).get("Ref") != null) { + Map<String, String> stringWithToken = new HashMap<>(); + ((Map) stringWithToken).put(ToscaFunctions.GET_INPUT.getFunctionName(), ((Map) refParameter).get("Ref")); + tokenPropertyValue.get("token").add(stringWithToken); + } else if (refParameter instanceof String) { + if (includeBooleanValue) { + StringBuilder booleanBuilder = new StringBuilder(); + String[] booleanValueList = ((String) refParameter).split(tokenChar); + for (int i = 0; i < booleanValueList.length; i++) { + if (i == 0) { + booleanBuilder.append(HeatBoolean.eval(booleanValueList[i])); + } else { + booleanBuilder.append(tokenChar); + booleanBuilder.append(HeatBoolean.eval(booleanValueList[i])); + } + } + tokenPropertyValue.get("token").add(booleanBuilder.toString()); + } else { + tokenPropertyValue.get("token").add(refParameter); + } + } + tokenPropertyValue.get("token").add(tokenChar); + tokenPropertyValue.get("token").add(substringIndex); + tokenPropertyValueList.add(tokenPropertyValue); } - } - tokenPropertyValue.get("token").add(booleanBuilder.toString()); - } else { - tokenPropertyValue.get("token").add(refParameter); + return Optional.of(tokenPropertyValueList); } - } - tokenPropertyValue.get("token").add(tokenChar); - tokenPropertyValue.get("token").add(substringIndex); - tokenPropertyValueList.add(tokenPropertyValue); } - - return Optional.of(tokenPropertyValueList); - - } + return Optional.empty(); } - - return Optional.empty(); - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java index 9a0865d6ed..205ef243c8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java @@ -13,8 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package org.openecomp.sdc.translator.services.heattotosca.helper; import java.util.ArrayList; @@ -25,7 +23,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -48,151 +45,109 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; public class ContrailV2VirtualMachineInterfaceHelper { - static Logger logger = - (Logger) LoggerFactory.getLogger(ContrailV2VirtualMachineInterfaceHelper.class); - /** - * Connect Virtual Machine Interface node template to network node template in TOSCA. - * - * @param resourceTranslationImpl resource translation implemetation - * @param translateTo translated ro object - * @param vmiNodeTemplate Virtual Machine Interface node template - */ - public void connectVmiToNetwork(ResourceTranslationBase resourceTranslationImpl, - TranslateTo translateTo, NodeTemplate vmiNodeTemplate) { - Object virtualNetworkRefs = - translateTo.getResource().getProperties() - .get(HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME); - if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) - || ((List) virtualNetworkRefs).size() == 0) { - return; - } - List<String> acceptableResourceTypes = Arrays - .asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - if (((List) virtualNetworkRefs).size() > 1) { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include '" - + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME - + "' property with more than one network values, only " - + "the first network will be connected, " - + "all rest will be ignored in TOSCA translation."); - } - Object virtualNetworkRef = ((List) virtualNetworkRefs).get(0); - - Optional<String> networkResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(virtualNetworkRef); - if (networkResourceId.isPresent()) { // get_resource - Resource networkResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), - translateTo.getHeatFileName()); - if (acceptableResourceTypes.contains(networkResource.getType())) { - Optional<String> resourceTranslatedId = - resourceTranslationImpl.getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), - translateTo.getContext()); - - if (resourceTranslatedId.isPresent()) { - RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( - vmiNodeTemplate, resourceTranslatedId.get()); - if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE - .equals(vmiNodeTemplate.getType())) { - ConsolidationDataUtil - .updateNodesConnectedOut(translateTo, resourceTranslatedId.get(), - ConsolidationEntityType.PORT, - ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); - } + static Logger logger = (Logger) LoggerFactory.getLogger(ContrailV2VirtualMachineInterfaceHelper.class); + + /** + * Connect Virtual Machine Interface node template to network node template in TOSCA. + * + * @param resourceTranslationImpl resource translation implemetation + * @param translateTo translated ro object + * @param vmiNodeTemplate Virtual Machine Interface node template + */ + public void connectVmiToNetwork(ResourceTranslationBase resourceTranslationImpl, TranslateTo translateTo, NodeTemplate vmiNodeTemplate) { + Object virtualNetworkRefs = translateTo.getResource().getProperties().get(HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME); + if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) || ((List) virtualNetworkRefs).size() == 0) { + return; } - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include '" + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME - + "' property which is connect to " - + "unsupported/incorrect resource with type '" - + networkResource.getType() - + "', therefore, this connection will be ignored in TOSCA translation."); - } - } else { - Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - virtualNetworkRef); - if (attachedResourceId.isPresent() && attachedResourceId.get().isGetParam() - && attachedResourceId.get().getEntityId() instanceof String) { - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam() - .get(attachedResourceId.get().getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( - vmiNodeTemplate, translatedSharedResourceId.getTranslatedId()); - - if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE - .equals(vmiNodeTemplate.getType())) { - ConsolidationDataUtil.updateNodesConnectedOut(translateTo, translatedSharedResourceId - .getTranslatedId(), ConsolidationEntityType.PORT, - ToscaConstants.LINK_REQUIREMENT_ID, - requirementAssignment); - } + List<String> acceptableResourceTypes = Arrays.asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + if (((List) virtualNetworkRefs).size() > 1) { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + translateTo.getResource().getType() + "' include '" + + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME + "' property with more than one network values, only " + + "the first network will be connected, " + "all rest will be ignored in TOSCA translation."); + } + Object virtualNetworkRef = ((List) virtualNetworkRefs).get(0); + Optional<String> networkResourceId = HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(virtualNetworkRef); + if (networkResourceId.isPresent()) { // get_resource + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), translateTo.getHeatFileName()); + if (acceptableResourceTypes.contains(networkResource.getType())) { + Optional<String> resourceTranslatedId = resourceTranslationImpl + .getResourceTranslatedId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), + translateTo.getContext()); + if (resourceTranslatedId.isPresent()) { + RequirementAssignment requirementAssignment = HeatToToscaUtil + .addLinkReqFromPortToNetwork(vmiNodeTemplate, resourceTranslatedId.get()); + if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE.equals(vmiNodeTemplate.getType())) { + ConsolidationDataUtil.updateNodesConnectedOut(translateTo, resourceTranslatedId.get(), ConsolidationEntityType.PORT, + ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + } + } + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + translateTo.getResource().getType() + "' include '" + + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME + "' property which is connect to " + + "unsupported/incorrect resource with type '" + networkResource.getType() + + "', therefore, this connection will be ignored in TOSCA translation."); + } + } else { + Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + virtualNetworkRef); + if (attachedResourceId.isPresent() && attachedResourceId.get().isGetParam() && attachedResourceId.get().getEntityId() instanceof String) { + TranslatedHeatResource translatedSharedResourceId = translateTo.getContext().getHeatSharedResourcesByParam() + .get(attachedResourceId.get().getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + RequirementAssignment requirementAssignment = HeatToToscaUtil + .addLinkReqFromPortToNetwork(vmiNodeTemplate, translatedSharedResourceId.getTranslatedId()); + if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE.equals(vmiNodeTemplate.getType())) { + ConsolidationDataUtil + .updateNodesConnectedOut(translateTo, translatedSharedResourceId.getTranslatedId(), ConsolidationEntityType.PORT, + ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + } + } + } } - } } - } - /** - * Check if the input heat resource is Vlan sub interface resource. - * - * @param resource heat resource to be checked - * @return true - if input resource is valn sub interface resource flase - otherwise. - */ - public boolean isVlanSubInterfaceResource(Resource resource) { - - if (resource.getType().equals(HeatResourcesTypes - .CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()) - && getVlanTagPropertyValue(resource).isPresent()) { - return true; + /** + * Check if the input heat resource is Vlan sub interface resource. + * + * @param resource heat resource to be checked + * @return true - if input resource is valn sub interface resource flase - otherwise. + */ + public boolean isVlanSubInterfaceResource(Resource resource) { + if (resource.getType().equals(HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()) + && getVlanTagPropertyValue(resource).isPresent()) { + return true; + } + return false; } - return false; - } - - public boolean isVlanSubInterfaceConnectedToPortIndirectly(TranslateTo translateTo) { - Resource resource = translateTo.getResource(); - TranslationContext context = translateTo.getContext(); - Set<String> nestedHeatsFiles = context.getNestedHeatsFiles(); - Map<String, Object> properties = resource.getProperties(); - - if (MapUtils.isNotEmpty(properties) - && properties.containsKey(HeatConstants.VMI_REFS_PROPERTY_NAME)) { - Map<String, Object> portReference = getPortReference(properties); - - return CollectionUtils.isNotEmpty(nestedHeatsFiles) - && nestedHeatsFiles.contains(translateTo.getHeatFileName()) - && portReference.containsKey(ResourceReferenceFunctions.GET_PARAM.getFunction()); + public boolean isVlanSubInterfaceConnectedToPortIndirectly(TranslateTo translateTo) { + Resource resource = translateTo.getResource(); + TranslationContext context = translateTo.getContext(); + Set<String> nestedHeatsFiles = context.getNestedHeatsFiles(); + Map<String, Object> properties = resource.getProperties(); + if (MapUtils.isNotEmpty(properties) && properties.containsKey(HeatConstants.VMI_REFS_PROPERTY_NAME)) { + Map<String, Object> portReference = getPortReference(properties); + return CollectionUtils.isNotEmpty(nestedHeatsFiles) && nestedHeatsFiles.contains(translateTo.getHeatFileName()) && portReference + .containsKey(ResourceReferenceFunctions.GET_PARAM.getFunction()); + } + return false; } - return false; - } - - private Map<String, Object> getPortReference(Map<String, Object> properties) { - Object portReferenceObj = properties.get(HeatConstants.VMI_REFS_PROPERTY_NAME); - List<Object> portReference = - portReferenceObj instanceof List ? (List<Object>) portReferenceObj : new ArrayList<>(); - return CollectionUtils.isEmpty(portReference) ? new HashMap<>() - : (Map<String, Object>) portReference.get(0); - } - - private Optional<Object> getVlanTagPropertyValue(Resource resource) { - Object vmiProperties = resource.getProperties() - .get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME); - if (vmiProperties != null && vmiProperties instanceof Map) { - return Optional.ofNullable(((Map) vmiProperties) - .get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME)); + private Map<String, Object> getPortReference(Map<String, Object> properties) { + Object portReferenceObj = properties.get(HeatConstants.VMI_REFS_PROPERTY_NAME); + List<Object> portReference = portReferenceObj instanceof List ? (List<Object>) portReferenceObj : new ArrayList<>(); + return CollectionUtils.isEmpty(portReference) ? new HashMap<>() : (Map<String, Object>) portReference.get(0); } - return Optional.empty(); - } - + private Optional<Object> getVlanTagPropertyValue(Resource resource) { + Object vmiProperties = resource.getProperties().get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME); + if (vmiProperties != null && vmiProperties instanceof Map) { + return Optional.ofNullable(((Map) vmiProperties).get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME)); + } + return Optional.empty(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java index ac6d317722..ec33420085 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java @@ -18,6 +18,7 @@ * ============LICENSE_END========================================================= */ package org.openecomp.sdc.translator.services.heattotosca.helper; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -73,7 +74,6 @@ public class ResourceTranslationNeutronPortHelper { properties.put(IP_REQUIREMENTS, ipRequirementsList); properties.put(MAC_REQUIREMENTS, createMacRequirement()); return properties; - } private Map<String, Object> createMacRequirement() { @@ -85,7 +85,7 @@ public class ResourceTranslationNeutronPortHelper { } private void setMacRequirements(Map<String, Object> properties) { - updateMacCountRequired(properties); + updateMacCountRequired(properties); } private void updateMacCountRequired(Map<String, Object> properties) { @@ -97,17 +97,16 @@ public class ResourceTranslationNeutronPortHelper { } private void setFloatingIpCount(Map<String, Object> properties) { - handleIpCountRequired(properties, ALLOWED_ADDRESS_PAIRS, FLOATING_IP_COUNT_REQUIRED ); + handleIpCountRequired(properties, ALLOWED_ADDRESS_PAIRS, FLOATING_IP_COUNT_REQUIRED); } private void setFixedIpCount(Map<String, Object> properties) { - handleIpCountRequired(properties, FIXED_IPS, IP_COUNT_REQUIRED ); + handleIpCountRequired(properties, FIXED_IPS, IP_COUNT_REQUIRED); } - private void addDefaultIpRequirement(Map<String, Object> properties) { List<Map<String, Object>> ipRequirementsList = ((List<Map<String, Object>>) properties.get(IP_REQUIREMENTS)); - if(ipRequirementsList.isEmpty()) { + if (ipRequirementsList.isEmpty()) { ipRequirementsList.add(createIPRequirement(DEFAULT_IP_VERSION)); } } @@ -124,52 +123,48 @@ public class ResourceTranslationNeutronPortHelper { return ipRequirements; } - private void handleIpCountRequired(Map<String, Object> properties, String ipType, String ipCountRequired ){ - + private void handleIpCountRequired(Map<String, Object> properties, String ipType, String ipCountRequired) { Object propertyValue = properties.get(ipType); - if(propertyValue == null){ + if (propertyValue == null) { return; } - if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { handleMapProperty(ipType, ipCountRequired, properties, (Map.Entry<String, Object>) ((Map) propertyValue).entrySet().iterator().next()); + } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { + handleListProperty(ipType, ipCountRequired, properties, (List) propertyValue); } - else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { - handleListProperty(ipType, ipCountRequired, properties, (List) propertyValue); - } - } - private void handleListProperty(String ipType, String ipCountRequired, Map<String, Object> properties, List propertyValue) { + private void handleListProperty(String ipType, String ipCountRequired, Map<String, Object> properties, List propertyValue) { for (int i = 0; i < propertyValue.size(); i++) { - handleIpAddress(ipType, ipCountRequired, properties, propertyValue.get(i)); + handleIpAddress(ipType, ipCountRequired, properties, propertyValue.get(i)); } } private void handleMapProperty(String ipType, String ipCountRequired, Map<String, Object> properties, Map.Entry<String, Object> mapEntry) { - updateIpCountRequired(ipType, ipCountRequired, properties, mapEntry.getValue()); + updateIpCountRequired(ipType, ipCountRequired, properties, mapEntry.getValue()); } private void handleIpAddress(String ipType, String ipCountRequired, Map<String, Object> properties, Object ipMap) { - if(ipMap instanceof Map && !((Map) ipMap).isEmpty()) { + if (ipMap instanceof Map && !((Map) ipMap).isEmpty()) { Object ipAddressMap = ((Map) ipMap).get(IP_ADDRESS); if (ipAddressMap instanceof Map && !((Map) ipAddressMap).isEmpty()) { Object ipInput = ((Map) ipAddressMap).get(GET_INPUT); - updateIpCountRequired(ipType, ipCountRequired, properties, ipInput); + updateIpCountRequired(ipType, ipCountRequired, properties, ipInput); } } } private void updateIpCountRequired(String ipType, String ipCountRequired, Map<String, Object> properties, Object ipInput) { Object ipVersion = getVersion(ipInput, ipType); - updateIpCountRequiredForVersion(ipCountRequired, properties, ipVersion); + updateIpCountRequiredForVersion(ipCountRequired, properties, ipVersion); } - private void updateIpCountRequiredForVersion(String ipCountRequired, Map<String, Object> properties, Object ipVersion) { + private void updateIpCountRequiredForVersion(String ipCountRequired, Map<String, Object> properties, Object ipVersion) { if (ipVersion != null) { HashMap<Object, Map<String, Object>> ipRequirementsMap = getIPRequirements(properties); - Map<String, Object> ipRequirement = ipRequirementsMap.get(ipVersion); - if (ipRequirement == null){ + Map<String, Object> ipRequirement = ipRequirementsMap.get(ipVersion); + if (ipRequirement == null) { ipRequirement = addIPRequirement(properties, ipVersion); } updateIpCountRequired(ipCountRequired, ipRequirement); @@ -177,56 +172,51 @@ public class ResourceTranslationNeutronPortHelper { } private Map<String, Object> addIPRequirement(Map<String, Object> properties, Object ipVersion) { - List<Map<String, Object>> ipRequirementsList = ((List<Map<String,Object>>) properties.get(IP_REQUIREMENTS)); + List<Map<String, Object>> ipRequirementsList = ((List<Map<String, Object>>) properties.get(IP_REQUIREMENTS)); Map<String, Object> newIpRequirement = createIPRequirement(ipVersion); ipRequirementsList.add(newIpRequirement); return newIpRequirement; } private void updateIpCountRequired(String ipCountRequired, Map<String, Object> ipRequirement) { - Map<String, Object> isIPCountRequired = (Map<String, Object>)ipRequirement.get(ipCountRequired); + Map<String, Object> isIPCountRequired = (Map<String, Object>) ipRequirement.get(ipCountRequired); isIPCountRequired.put(IS_REQUIRED, Boolean.TRUE); } - private HashMap <Object, Map<String, Object>> getIPRequirements (Map<String, Object> properties) { + private HashMap<Object, Map<String, Object>> getIPRequirements(Map<String, Object> properties) { HashMap<Object, Map<String, Object>> ipRequirementsMap = new HashMap<>(); - List<Map<String, Object>> ipRequirementsList = ((List<Map<String,Object>>) properties.get(IP_REQUIREMENTS)); - ipRequirementsList.stream().forEach(e->ipRequirementsMap.put(e.get(IP_VERSION),e)); + List<Map<String, Object>> ipRequirementsList = ((List<Map<String, Object>>) properties.get(IP_REQUIREMENTS)); + ipRequirementsList.stream().forEach(e -> ipRequirementsMap.put(e.get(IP_VERSION), e)); return ipRequirementsMap; } private void setNetworkRoleTag(Map<String, Object> properties) { Object propertyValue = properties.get(NETWORK); if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { - Map.Entry<String, String> mapEntry = - (Map.Entry<String, String>) ((Map) propertyValue).entrySet().iterator().next(); - if (mapEntry.getValue() instanceof String && getNetworkRole(mapEntry.getValue())!=null) { + Map.Entry<String, String> mapEntry = (Map.Entry<String, String>) ((Map) propertyValue).entrySet().iterator().next(); + if (mapEntry.getValue() instanceof String && getNetworkRole(mapEntry.getValue()) != null) { properties.put(NETWORK_ROLE_TAG, getNetworkRole(mapEntry.getValue())); } } } private Object getVersion(Object value, String type) { - Object version = null; - if(type.equals(FIXED_IPS)){ - version = getIpVersion(value); - } - else if(type.equals(ALLOWED_ADDRESS_PAIRS)){ - version = getFloatingIpVersion(value); + if (type.equals(FIXED_IPS)) { + version = getIpVersion(value); + } else if (type.equals(ALLOWED_ADDRESS_PAIRS)) { + version = getFloatingIpVersion(value); } return version; } private Object getFloatingIpVersion(Object value) { Object ipVersion = null; - // Allowed ONLY String parameter - if(value instanceof String) { + if (value instanceof String) { if (((String) value).endsWith(FLOATING_V6_IP)) { ipVersion = 6; - } - else if (((String) value).endsWith(FLOATING_IP)){ + } else if (((String) value).endsWith(FLOATING_IP)) { ipVersion = 4; } } @@ -234,18 +224,15 @@ public class ResourceTranslationNeutronPortHelper { } private Object getIpVersion(Object value) { - // Allowed List or String parameter Object ipVersion = null; - if (value instanceof List && !((List) value).isEmpty()){ + if (value instanceof List && !((List) value).isEmpty()) { value = ((List) value).get(0); } - - if(value instanceof String) { + if (value instanceof String) { if (((String) value).endsWith(V6_IPS) || ((String) value).matches(IPV6_REGEX)) { ipVersion = 6; - } - else { + } else { ipVersion = 4; } } @@ -254,15 +241,13 @@ public class ResourceTranslationNeutronPortHelper { private Object getNetworkRole(String value) { Object networkRole = null; - if(value.endsWith(NET_NAME)) { + if (value.endsWith(NET_NAME)) { networkRole = value.substring(0, value.length() - NET_NAME.length()); - } - else if(value.endsWith(NET_ID)) { + } else if (value.endsWith(NET_ID)) { networkRole = value.substring(0, value.length() - NET_ID.length()); - } - else if(value.endsWith(NET_FQDN)) { + } else if (value.endsWith(NET_FQDN)) { networkRole = value.substring(0, value.length() - NET_FQDN.length()); } return networkRole; } -}
\ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java index 6328541927..0a3b1e8954 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.helper; import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE; @@ -29,7 +28,6 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.heat.datatypes.manifest.FileData; @@ -45,126 +43,112 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; public class VolumeTranslationHelper { - private final Logger logger; - public VolumeTranslationHelper(Logger logger) { - this.logger = logger; - } - /** - * Gets file data containing volume. - * - * @param filesToSearch the files to search - * @param resourceId the resource id - * @param translateTo the translate to - * @param types the types - * @return the file data containing volume - */ - public Optional<ResourceFileDataAndIDs> getFileDataContainingVolume(List<FileData> filesToSearch, - String resourceId, - TranslateTo translateTo, - FileData.Type... types) { - if (CollectionUtils.isEmpty(filesToSearch)) { - return Optional.empty(); + private final Logger logger; + + public VolumeTranslationHelper(Logger logger) { + this.logger = logger; } - List<FileData> fileDatas = Objects.isNull(types) ? filesToSearch : HeatToToscaUtil - .getFilteredListOfFileDataByTypes(filesToSearch, types); - Optional<ResourceFileDataAndIDs> fileDataAndIDs = - getResourceFileDataAndIDsForVolumeConnection(resourceId, translateTo, fileDatas); - if (fileDataAndIDs.isPresent()) { - return fileDataAndIDs; + /** + * Gets file data containing volume. + * + * @param filesToSearch the files to search + * @param resourceId the resource id + * @param translateTo the translate to + * @param types the types + * @return the file data containing volume + */ + public Optional<ResourceFileDataAndIDs> getFileDataContainingVolume(List<FileData> filesToSearch, String resourceId, TranslateTo translateTo, + FileData.Type... types) { + if (CollectionUtils.isEmpty(filesToSearch)) { + return Optional.empty(); + } + List<FileData> fileDatas = Objects.isNull(types) ? filesToSearch : HeatToToscaUtil.getFilteredListOfFileDataByTypes(filesToSearch, types); + Optional<ResourceFileDataAndIDs> fileDataAndIDs = getResourceFileDataAndIDsForVolumeConnection(resourceId, translateTo, fileDatas); + if (fileDataAndIDs.isPresent()) { + return fileDataAndIDs; + } + return Optional.empty(); } - return Optional.empty(); - } - private Optional<ResourceFileDataAndIDs> getResourceFileDataAndIDsForVolumeConnection( - String resourceId, TranslateTo translateTo, List<FileData> fileDatas) { - for (FileData data : fileDatas) { - HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() - .yamlToObject(translateTo.getContext().getFiles().getFileContentAsStream(data.getFile()), - HeatOrchestrationTemplate.class); - Map<String, Output> outputs = heatOrchestrationTemplate.getOutputs(); - if (Objects.isNull(outputs)) { - continue; - } - Output output = outputs.get(resourceId); - if (Objects.nonNull(output)) { - Optional<AttachedResourceId> attachedOutputId = HeatToToscaUtil - .extractAttachedResourceId(data.getFile(), heatOrchestrationTemplate, - translateTo.getContext(), output.getValue()); - if (attachedOutputId.isPresent()) { - AttachedResourceId attachedResourceId = attachedOutputId.get(); - if (!isOutputIsGetResource(resourceId, data, attachedResourceId)) { - continue; - } - String translatedId = (String) attachedResourceId.getTranslatedId(); - if (isOutputOfTypeCinderVolume(translateTo, data, heatOrchestrationTemplate, - translatedId)) { - ResourceFileDataAndIDs fileDataAndIDs = - new ResourceFileDataAndIDs((String) attachedResourceId.getEntityId(), - translatedId, - data); - return Optional.of(fileDataAndIDs); - } else { - logger.warn( - "output: '" + resourceId + "' in file '" + data.getFile() + "' is not of type '" - + CINDER_VOLUME_RESOURCE_TYPE.getHeatResource() + "'"); - } + private Optional<ResourceFileDataAndIDs> getResourceFileDataAndIDsForVolumeConnection(String resourceId, TranslateTo translateTo, + List<FileData> fileDatas) { + for (FileData data : fileDatas) { + HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translateTo.getContext().getFiles().getFileContentAsStream(data.getFile()), HeatOrchestrationTemplate.class); + Map<String, Output> outputs = heatOrchestrationTemplate.getOutputs(); + if (Objects.isNull(outputs)) { + continue; + } + Output output = outputs.get(resourceId); + if (Objects.nonNull(output)) { + Optional<AttachedResourceId> attachedOutputId = HeatToToscaUtil + .extractAttachedResourceId(data.getFile(), heatOrchestrationTemplate, translateTo.getContext(), output.getValue()); + if (attachedOutputId.isPresent()) { + AttachedResourceId attachedResourceId = attachedOutputId.get(); + if (!isOutputIsGetResource(resourceId, data, attachedResourceId)) { + continue; + } + String translatedId = (String) attachedResourceId.getTranslatedId(); + if (isOutputOfTypeCinderVolume(translateTo, data, heatOrchestrationTemplate, translatedId)) { + ResourceFileDataAndIDs fileDataAndIDs = new ResourceFileDataAndIDs((String) attachedResourceId.getEntityId(), translatedId, + data); + return Optional.of(fileDataAndIDs); + } else { + logger.warn("output: '" + resourceId + "' in file '" + data.getFile() + "' is not of type '" + CINDER_VOLUME_RESOURCE_TYPE + .getHeatResource() + "'"); + } + } + } else { + logger.warn("output: '" + resourceId + "' in file '" + data.getFile() + "' is not found"); + } } - } else { - logger.warn("output: '" + resourceId + "' in file '" + data.getFile() + "' is not found"); - } + return Optional.empty(); } - return Optional.empty(); - } - private boolean isOutputOfTypeCinderVolume(TranslateTo translateTo, FileData data, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedId) { - return getResourceByTranslatedResourceId(data.getFile(), heatOrchestrationTemplate, - translatedId, translateTo, CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()).isPresent(); - } + private boolean isOutputOfTypeCinderVolume(TranslateTo translateTo, FileData data, HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedId) { + return getResourceByTranslatedResourceId(data.getFile(), heatOrchestrationTemplate, translatedId, translateTo, + CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()).isPresent(); + } - private Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId( - String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId, TranslateTo translateTo, String heatResourceType) { - List<Map.Entry<String, Resource>> list = heatOrchestrationTemplate.getResources().entrySet() - .stream() - .filter( - entry -> getPredicatesForTranslatedIdToResourceId(fileName, heatOrchestrationTemplate, - translatedResourceId, translateTo.getContext(), heatResourceType) - .stream() - .allMatch(p -> p.test(entry))) - .collect(Collectors.toList()); - if (CollectionUtils.isEmpty(list)) { - return Optional.empty(); - } else { - return Optional.of(list); + private Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId(String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, TranslateTo translateTo, + String heatResourceType) { + List<Map.Entry<String, Resource>> list = heatOrchestrationTemplate.getResources().entrySet().stream().filter( + entry -> getPredicatesForTranslatedIdToResourceId(fileName, heatOrchestrationTemplate, translatedResourceId, translateTo.getContext(), + heatResourceType).stream().allMatch(p -> p.test(entry))).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(list)) { + return Optional.empty(); + } else { + return Optional.of(list); + } } - } - private List<Predicate<Map.Entry<String, Resource>>> getPredicatesForTranslatedIdToResourceId( - String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId, TranslationContext context, String heatResourceType) { - List<Predicate<Map.Entry<String, Resource>>> list = new ArrayList<>(); - list.add(entry -> entry.getValue().getType().equals(heatResourceType)); - list.add(entry -> { - Optional<String> resourceTranslatedId = ResourceTranslationBase - .getResourceTranslatedId(fileName, heatOrchestrationTemplate, entry.getKey(), context); - return resourceTranslatedId.isPresent() - && resourceTranslatedId.get().equals(translatedResourceId); - }); - return list; - } + private List<Predicate<Map.Entry<String, Resource>>> getPredicatesForTranslatedIdToResourceId(String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, + TranslationContext context, + String heatResourceType) { + List<Predicate<Map.Entry<String, Resource>>> list = new ArrayList<>(); + list.add(entry -> entry.getValue().getType().equals(heatResourceType)); + list.add(entry -> { + Optional<String> resourceTranslatedId = ResourceTranslationBase + .getResourceTranslatedId(fileName, heatOrchestrationTemplate, entry.getKey(), context); + return resourceTranslatedId.isPresent() && resourceTranslatedId.get().equals(translatedResourceId); + }); + return list; + } - private boolean isOutputIsGetResource(String resourceId, FileData data, - AttachedResourceId attachedResourceId) { - if (attachedResourceId.isGetResource()) { - return true; - } else { - logger.warn("output: '" + resourceId + "' in file '" + data.getFile() - + "' is not defined as get_resource and therefore not supported as shared resource."); - return false; + private boolean isOutputIsGetResource(String resourceId, FileData data, AttachedResourceId attachedResourceId) { + if (attachedResourceId.isGetResource()) { + return true; + } else { + logger.warn("output: '" + resourceId + "' in file '" + data.getFile() + + "' is not defined as get_resource and therefore not supported as shared resource."); + return false; + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java index aad57e0d5e..f65dc888f8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR; @@ -26,7 +25,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - import org.apache.commons.lang3.StringUtils; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; @@ -44,16 +42,14 @@ import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslatio public class FunctionTranslationGetAttrImpl implements FunctionTranslation { private static List<Object> translateGetAttributeFunctionExpression(FunctionTranslator functionTranslator) { - List<Object> attributeParamList = (List) functionTranslator.getFunctionValue(); List<Object> toscaAttributeParamList = new ArrayList<>(); - Optional<String> targetResourceTranslatedId = Optional.empty(); String targetResourceId = null; if (attributeParamList.get(0) instanceof String) { targetResourceId = (String) attributeParamList.get(0); targetResourceTranslatedId = handleResourceName(targetResourceId, functionTranslator.getHeatFileName(), - functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext()); + functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext()); } if (!targetResourceTranslatedId.isPresent()) { //unsupported resource @@ -65,98 +61,80 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { if (!toscaAttList.isPresent()) { //Unsupported attribute toscaAttributeParamList.clear(); - toscaAttributeParamList.add(functionTranslator.getUnsupportedAttributePrefix() - + attributeParamList.get(0) + "." + attributeParamList.get(1)); + toscaAttributeParamList + .add(functionTranslator.getUnsupportedAttributePrefix() + attributeParamList.get(0) + "." + attributeParamList.get(1)); return toscaAttributeParamList; } toscaAttributeParamList.addAll(toscaAttList.get()); - handleGetAttrConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId.get(), - toscaAttList.get()); - - String resourceType = HeatToToscaUtil.getResourceType((String) attributeParamList.get(0), functionTranslator - .getHeatOrchestrationTemplate(), functionTranslator.getHeatFileName()); - Optional<List<Object>> toscaIndexOrKey = handleAttributeIndexOrKey(functionTranslator, resourceType, - attributeParamList); + handleGetAttrConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId.get(), toscaAttList.get()); + String resourceType = HeatToToscaUtil.getResourceType((String) attributeParamList.get(0), functionTranslator.getHeatOrchestrationTemplate(), + functionTranslator.getHeatFileName()); + Optional<List<Object>> toscaIndexOrKey = handleAttributeIndexOrKey(functionTranslator, resourceType, attributeParamList); toscaIndexOrKey.ifPresent(toscaAttributeParamList::addAll); return toscaAttributeParamList; } - private static void handleGetAttrConsolidationData(FunctionTranslator functionTranslator, - String targetResourceId, - String targetResourceTranslatedId, - List<Object> toscaAttList) { + private static void handleGetAttrConsolidationData(FunctionTranslator functionTranslator, String targetResourceId, + String targetResourceTranslatedId, List<Object> toscaAttList) { Optional<String> resourceTranslatedId; String resourceId = functionTranslator.getResourceId(); String resourceTranslatedIdValue = null; if (resourceId != null) { resourceTranslatedId = handleResourceName(resourceId, functionTranslator.getHeatFileName(), - functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext()); + functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext()); if (resourceTranslatedId.isPresent()) { resourceTranslatedIdValue = resourceTranslatedId.get(); - handleGetAttrOutConsolidationData(functionTranslator, targetResourceTranslatedId, - resourceTranslatedIdValue, toscaAttList); + handleGetAttrOutConsolidationData(functionTranslator, targetResourceTranslatedId, resourceTranslatedIdValue, toscaAttList); } } - handleGetAttrInConsolidationData(functionTranslator, resourceTranslatedIdValue, - targetResourceId, targetResourceTranslatedId, toscaAttList); + handleGetAttrInConsolidationData(functionTranslator, resourceTranslatedIdValue, targetResourceId, targetResourceTranslatedId, toscaAttList); } - private static void handleGetAttrOutConsolidationData(FunctionTranslator functionTranslator, - String targetTranslatedResourceId, - String resourceTranslatedId, - List<Object> toscaAttList) { + private static void handleGetAttrOutConsolidationData(FunctionTranslator functionTranslator, String targetTranslatedResourceId, + String resourceTranslatedId, List<Object> toscaAttList) { if (functionTranslator.getServiceTemplate() == null) { return; } - String attName = (String) toscaAttList.get(0); - ConsolidationDataUtil.updateNodeGetAttributeOut(functionTranslator, targetTranslatedResourceId, - resourceTranslatedId, attName); - + ConsolidationDataUtil.updateNodeGetAttributeOut(functionTranslator, targetTranslatedResourceId, resourceTranslatedId, attName); } - private static void handleGetAttrInConsolidationData(FunctionTranslator functionTranslator, - String resourceTranslatedId, - String targetResourceId, - String targetResourceTranslatedId, - List<Object> toscaAttList) { + private static void handleGetAttrInConsolidationData(FunctionTranslator functionTranslator, String resourceTranslatedId, String targetResourceId, + String targetResourceTranslatedId, List<Object> toscaAttList) { if (functionTranslator.getServiceTemplate() == null) { return; } String attName = (String) toscaAttList.get(0); if (Objects.nonNull(resourceTranslatedId)) { - ConsolidationDataUtil.updateNodeGetAttributeIn(functionTranslator, resourceTranslatedId, - targetResourceId, targetResourceTranslatedId, attName); + ConsolidationDataUtil + .updateNodeGetAttributeIn(functionTranslator, resourceTranslatedId, targetResourceId, targetResourceTranslatedId, attName); } else { - ConsolidationDataUtil.updateOutputParamGetAttrIn(functionTranslator, targetResourceId, - targetResourceTranslatedId, functionTranslator.getPropertyName(), attName); + ConsolidationDataUtil + .updateOutputParamGetAttrIn(functionTranslator, targetResourceId, targetResourceTranslatedId, functionTranslator.getPropertyName(), + attName); } } - private static Optional<List<Object>> handleAttributeIndexOrKey(FunctionTranslator functionTranslator, - String resourceType, + private static Optional<List<Object>> handleAttributeIndexOrKey(FunctionTranslator functionTranslator, String resourceType, List<Object> attributeParamList) { - List<Object> attributeIndexOrKey = new ArrayList<>(); if (attributeParamList.size() < 3) { return Optional.empty(); } - for (int i = 2; i < attributeParamList.size(); i++) { if (isInteger(attributeParamList.get(i))) { attributeIndexOrKey.add(attributeParamList.get(i)); } else if (attributeParamList.get(i) instanceof Map) { attributeIndexOrKey.add(getToscaAttributeValue(functionTranslator, attributeParamList.get(i))); } else { - Object toscaAttributeName = resourceType == null ? null : functionTranslator.getContext() - .getElementMapping(resourceType, Constants.ATTR, getAttributeFullPath(attributeParamList, i)); + Object toscaAttributeName = resourceType == null ? null + : functionTranslator.getContext().getElementMapping(resourceType, Constants.ATTR, getAttributeFullPath(attributeParamList, i)); if (toscaAttributeName == null) { toscaAttributeName = attributeParamList.get(i); } attributeIndexOrKey.add(toscaAttributeName); } } - return Optional.of(attributeIndexOrKey); } @@ -183,18 +161,15 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { return StringUtils.isNumeric(String.valueOf(inputNumber)); } - private static Optional<String> handleResourceName(String resourceId, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private static Optional<String> handleResourceName(String resourceId, String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { - return ResourceTranslationBase - .getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); + return ResourceTranslationBase.getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); } - private static Optional<List<Object>> handleAttributeName(List<Object> attributeParamList, - FunctionTranslator functionTranslator) { + private static Optional<List<Object>> handleAttributeName(List<Object> attributeParamList, FunctionTranslator functionTranslator) { String resourceId = (String) attributeParamList.get(0); - Resource resource = HeatToToscaUtil.getResource(functionTranslator.getHeatOrchestrationTemplate(), - resourceId, functionTranslator.getHeatFileName()); + Resource resource = HeatToToscaUtil + .getResource(functionTranslator.getHeatOrchestrationTemplate(), resourceId, functionTranslator.getHeatFileName()); if (attributeParamList.size() == 1) { return getResourceTranslatedAttributesList(resource, functionTranslator.getContext()); } @@ -204,8 +179,7 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { if (HeatToToscaUtil.isNestedResource(resource)) { return getNestedResourceTranslatedAttribute((String) attributeParamList.get(1)); } else { - return getResourceTranslatedAttribute(resource, (String) attributeParamList.get(1), functionTranslator - .getContext()); + return getResourceTranslatedAttribute(resource, (String) attributeParamList.get(1), functionTranslator.getContext()); } } @@ -227,8 +201,7 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { return Optional.of(translatedAttributesList); } - private static Optional<List<Object>> getResourceTranslatedAttributesList(Resource resource, - TranslationContext context) { + private static Optional<List<Object>> getResourceTranslatedAttributesList(Resource resource, TranslationContext context) { List<Object> translatedAttributes = new ArrayList<>(); if (HeatToToscaUtil.isNestedResource(resource)) { Optional<String> nestedFile = HeatToToscaUtil.getNestedFile(resource); @@ -236,13 +209,11 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { return Optional.empty(); } HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(context.getFiles().getFileContentAsStream(nestedFile.get()), HeatOrchestrationTemplate.class); + .yamlToObject(context.getFiles().getFileContentAsStream(nestedFile.get()), HeatOrchestrationTemplate.class); translatedAttributes.addAll(nestedHeatOrchestrationTemplate.getOutputs().keySet()); return Optional.of(translatedAttributes); - } else { - Map<String, String> resourceMappingAttributes = - context.getElementMapping(resource.getType(), Constants.ATTR); + Map<String, String> resourceMappingAttributes = context.getElementMapping(resource.getType(), Constants.ATTR); if (resourceMappingAttributes == null) { return Optional.empty(); } @@ -252,9 +223,7 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { } } - private static Optional<List<Object>> getResourceTranslatedAttribute(Resource resource, - String attributeName, - TranslationContext context) { + private static Optional<List<Object>> getResourceTranslatedAttribute(Resource resource, String attributeName, TranslationContext context) { List<Object> translatedAttributesList = new ArrayList<>(); String translatedAttribute = context.getElementMapping(resource.getType(), Constants.ATTR, attributeName); if (translatedAttribute != null) { @@ -265,13 +234,10 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { } } - private static Object getToscaAttributeValue(FunctionTranslator functionTranslator, - Object attributeVal) { + private static Object getToscaAttributeValue(FunctionTranslator functionTranslator, Object attributeVal) { if (attributeVal instanceof Map && !((Map) attributeVal).isEmpty()) { - Map.Entry<String, Object> functionMapEntry = - (Map.Entry<String, Object>) ((Map) attributeVal).entrySet().iterator().next(); - Optional<FunctionTranslation> functionTranslationInstance = - FunctionTranslationFactory.getInstance(functionMapEntry.getKey()); + Map.Entry<String, Object> functionMapEntry = (Map.Entry<String, Object>) ((Map) attributeVal).entrySet().iterator().next(); + Optional<FunctionTranslation> functionTranslationInstance = FunctionTranslationFactory.getInstance(functionMapEntry.getKey()); if (functionTranslationInstance.isPresent()) { functionTranslator.setFunctionValue(functionMapEntry.getValue()); return functionTranslationInstance.get().translateFunction(functionTranslator); @@ -295,8 +261,8 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { public Object translateFunction(FunctionTranslator functionTranslator) { Object returnValue; List<Object> attributeFunctionExpression = translateGetAttributeFunctionExpression(functionTranslator); - if (functionTranslator.isResourceSupported(attributeFunctionExpression.get(0).toString()) - && functionTranslator.isAttributeSupported(attributeFunctionExpression.get(0).toString())) { + if (functionTranslator.isResourceSupported(attributeFunctionExpression.get(0).toString()) && functionTranslator + .isAttributeSupported(attributeFunctionExpression.get(0).toString())) { Map<String, Object> getAttrValue = new HashMap<>(); getAttrValue.put(ToscaFunctions.GET_ATTRIBUTE.getFunctionName(), attributeFunctionExpression); returnValue = getAttrValue; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java index b81f8fbe33..253410e493 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.onap.sdc.tosca.datatypes.model.ArtifactDefinition; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.ToscaArtifactType; @@ -25,14 +28,9 @@ import org.openecomp.sdc.tosca.services.ToscaFileOutputService; import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class FunctionTranslationGetFileImpl implements FunctionTranslation { - private static ArtifactDefinition createArtifactDefinition(Object function, - ToscaFileOutputService toscaFileOutputService) { + + private static ArtifactDefinition createArtifactDefinition(Object function, ToscaFileOutputService toscaFileOutputService) { ArtifactDefinition artifactDefinition = new ArtifactDefinition(); artifactDefinition.setType(ToscaArtifactType.NATIVE_DEPLOYMENT); artifactDefinition.setFile("../" + toscaFileOutputService.getArtifactsFolderName() + "/" + function); @@ -41,7 +39,6 @@ public class FunctionTranslationGetFileImpl implements FunctionTranslation { @Override public Object translateFunction(FunctionTranslator functionTranslator) { - String file = ((String) functionTranslator.getFunctionValue()).replace("file:///", ""); final String artifactId = file.split("\\.")[0]; Map<String, Object> returnValue = new HashMap<>(); @@ -49,7 +46,6 @@ public class FunctionTranslationGetFileImpl implements FunctionTranslation { artifactParameters.add(ToscaConstants.MODELABLE_ENTITY_NAME_SELF); returnValue.put(ToscaFunctions.GET_ARTIFACT.getFunctionName(), artifactParameters); artifactParameters.add(artifactId); - ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl(); if (functionTranslator.getToscaTemplate() instanceof NodeTemplate) { NodeTemplate nodeTemplate = (NodeTemplate) functionTranslator.getToscaTemplate(); @@ -61,5 +57,4 @@ public class FunctionTranslationGetFileImpl implements FunctionTranslation { } return returnValue; } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java index 793799e5f0..e7257dd9f4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; import java.util.ArrayList; @@ -21,21 +20,21 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; - import org.openecomp.sdc.heat.datatypes.model.HeatPseudoParameters; import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; public class FunctionTranslationGetParamImpl implements FunctionTranslation { + private static Object translateGetParamFunctionExpression(FunctionTranslator functionTranslator) { Object functionValue = functionTranslator.getFunctionValue(); Object returnValue = null; if (functionValue instanceof String) { returnValue = functionValue; if (HeatPseudoParameters.getPseudoParameterNames().contains(functionValue)) { - functionTranslator.getContext().addUsedHeatPseudoParams(functionTranslator.getHeatFileName(), - (String) functionValue, (String) functionValue); + functionTranslator.getContext() + .addUsedHeatPseudoParams(functionTranslator.getHeatFileName(), (String) functionValue, (String) functionValue); } } else if (functionValue instanceof List) { returnValue = new ArrayList<>(); @@ -49,15 +48,13 @@ public class FunctionTranslationGetParamImpl implements FunctionTranslation { } } } - return returnValue; } private static Object translatedInnerMap(FunctionTranslator functionTranslator, Map<String, Object> paramMap) { Map<String, Object> translatedInnerMapValue = new HashMap<>(); for (Map.Entry<String, Object> entry : paramMap.entrySet()) { - Optional<FunctionTranslation> functionTranslationInstance = - FunctionTranslationFactory.getInstance(entry.getKey()); + Optional<FunctionTranslation> functionTranslationInstance = FunctionTranslationFactory.getInstance(entry.getKey()); if (functionTranslationInstance.isPresent()) { functionTranslator.setFunctionValue(entry.getValue()); return functionTranslationInstance.get().translateFunction(functionTranslator); @@ -68,8 +65,7 @@ public class FunctionTranslationGetParamImpl implements FunctionTranslation { return translatedInnerMapValue; } - private static Object translatedInnerValue(FunctionTranslator functionTranslator, - Object value) { + private static Object translatedInnerValue(FunctionTranslator functionTranslator, Object value) { if (value instanceof String) { return value; } else if (value instanceof Map) { @@ -81,15 +77,13 @@ public class FunctionTranslationGetParamImpl implements FunctionTranslation { } return returnedList; } - return value; } @Override public Object translateFunction(FunctionTranslator functionTranslator) { Map<String, Object> returnValue = new HashMap<>(); - returnValue.put(ToscaFunctions.GET_INPUT.getFunctionName(), - translateGetParamFunctionExpression(functionTranslator)); + returnValue.put(ToscaFunctions.GET_INPUT.getFunctionName(), translateGetParamFunctionExpression(functionTranslator)); return returnValue; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java index 383ee5075b..c4feb54f1e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java @@ -13,23 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; +import java.util.Optional; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; -import java.util.Optional; - public class FunctionTranslationGetResourceImpl implements FunctionTranslation { + @Override public Object translateFunction(FunctionTranslator functionTranslator) { Object returnValue; - Optional<String> resourceTranslatedId = ResourceTranslationBase.getResourceTranslatedId(functionTranslator - .getHeatFileName(), functionTranslator.getHeatOrchestrationTemplate(), + Optional<String> resourceTranslatedId = ResourceTranslationBase + .getResourceTranslatedId(functionTranslator.getHeatFileName(), functionTranslator.getHeatOrchestrationTemplate(), (String) functionTranslator.getFunctionValue(), functionTranslator.getContext()); - returnValue = resourceTranslatedId.orElseGet(() -> functionTranslator.getUnsupportedResourcePrefix() - + functionTranslator.getFunctionValue()); + returnValue = resourceTranslatedId.orElseGet(() -> functionTranslator.getUnsupportedResourcePrefix() + functionTranslator.getFunctionValue()); return returnValue; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslator.java index 768f531938..38516df225 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -26,7 +25,6 @@ public class FunctionTranslator { private static final String UNSUPPORTED_RESOURCE_PREFIX = "UNSUPPORTED_RESOURCE_"; private static final String UNSUPPORTED_ATTRIBUTE_PREFIX = "UNSUPPORTED_ATTRIBUTE_"; - private ServiceTemplate serviceTemplate; private String resourceId; private String propertyName; @@ -40,8 +38,7 @@ public class FunctionTranslator { //default constructor } - public FunctionTranslator(TranslateTo functionTranslateTo, String propertyName, Object functionValue, - Template toscaTemplate) { + public FunctionTranslator(TranslateTo functionTranslateTo, String propertyName, Object functionValue, Template toscaTemplate) { this.serviceTemplate = functionTranslateTo.getServiceTemplate(); this.resourceId = functionTranslateTo.getResourceId(); this.propertyName = propertyName; @@ -52,11 +49,9 @@ public class FunctionTranslator { this.context = functionTranslateTo.getContext(); } - public static TranslateTo getFunctionTranslateTo(ServiceTemplate serviceTemplate, String resourceId, - String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - return new TranslateTo(heatFileName, serviceTemplate, heatOrchestrationTemplate, null, resourceId, null, - context); + public static TranslateTo getFunctionTranslateTo(ServiceTemplate serviceTemplate, String resourceId, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { + return new TranslateTo(heatFileName, serviceTemplate, heatOrchestrationTemplate, null, resourceId, null, context); } public ServiceTemplate getServiceTemplate() { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java index cbb53ab831..5e68b41a38 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; +import static org.openecomp.sdc.tosca.services.ToscaConstants.HEAT_NODE_TYPE_SUFFIX; + +import java.util.List; +import java.util.Optional; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; @@ -23,23 +26,14 @@ import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.NameExtractorUtil; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; -import java.util.List; -import java.util.Optional; - -import static org.openecomp.sdc.tosca.services.ToscaConstants.HEAT_NODE_TYPE_SUFFIX; - public class NameExtractorContrailComputeImpl implements NameExtractor { @Override public String extractNodeTypeName(Resource resource, String resourceId, String translatedId) { ContrailTranslationHelper contrailTranslationHelper = new ContrailTranslationHelper(); - List<PropertyRegexMatcher> propertyRegexMatchers = - contrailTranslationHelper.getPropertyRegexMatchersForComputeNodeType(); - Optional<String> extractedNodeTypeName = NameExtractorUtil.extractNodeTypeNameByPropertiesPriority(resource - .getProperties(), propertyRegexMatchers); - - return ToscaNodeType.VFC_NODE_TYPE_PREFIX + HEAT_NODE_TYPE_SUFFIX - + (extractedNodeTypeName.orElseGet(() -> "compute_" + translatedId)); + List<PropertyRegexMatcher> propertyRegexMatchers = contrailTranslationHelper.getPropertyRegexMatchersForComputeNodeType(); + Optional<String> extractedNodeTypeName = NameExtractorUtil + .extractNodeTypeNameByPropertiesPriority(resource.getProperties(), propertyRegexMatchers); + return ToscaNodeType.VFC_NODE_TYPE_PREFIX + HEAT_NODE_TYPE_SUFFIX + (extractedNodeTypeName.orElseGet(() -> "compute_" + translatedId)); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java index 980e3ca9ba..14b95c0f94 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; +import static org.openecomp.sdc.tosca.services.ToscaConstants.HEAT_NODE_TYPE_SUFFIX; + +import java.util.List; +import java.util.Optional; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; @@ -23,24 +26,14 @@ import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.NameExtractorUtil; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationNovaServerImpl; -import java.util.List; -import java.util.Optional; - -import static org.openecomp.sdc.tosca.services.ToscaConstants.HEAT_NODE_TYPE_SUFFIX; - public class NameExtractorNovaServerImpl implements NameExtractor { @Override public String extractNodeTypeName(Resource resource, String resourceId, String translatedId) { ResourceTranslationNovaServerImpl novaServerTranslator = new ResourceTranslationNovaServerImpl(); - List<PropertyRegexMatcher> propertyRegexMatchers = - novaServerTranslator.getPropertyRegexMatchersForNovaNodeType(); - + List<PropertyRegexMatcher> propertyRegexMatchers = novaServerTranslator.getPropertyRegexMatchersForNovaNodeType(); Optional<String> extractedNodeTypeName = NameExtractorUtil - .extractNodeTypeNameByPropertiesPriority(resource.getProperties(), propertyRegexMatchers); - - return ToscaNodeType.VFC_NODE_TYPE_PREFIX + HEAT_NODE_TYPE_SUFFIX - + (extractedNodeTypeName.orElseGet(() -> translatedId.replace(".", "_"))); + .extractNodeTypeNameByPropertiesPriority(resource.getProperties(), propertyRegexMatchers); + return ToscaNodeType.VFC_NODE_TYPE_PREFIX + HEAT_NODE_TYPE_SUFFIX + (extractedNodeTypeName.orElseGet(() -> translatedId.replace(".", "_"))); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java index f3aaf710f8..76b147afff 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import java.util.ArrayList; @@ -23,7 +22,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -51,6 +49,7 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.errors.TranslatorErrorCodes; abstract class BaseResourceConnection<T> { + protected static Logger logger = LoggerFactory.getLogger(BaseResourceConnection.class); protected TranslateTo translateTo; FileData nestedFileData; @@ -58,9 +57,8 @@ abstract class BaseResourceConnection<T> { NodeType nodeType; ResourceTranslationBase resourceTranslationBase; - BaseResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, - FileData nestedFileData, NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { + BaseResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { this.translateTo = translateTo; this.nestedFileData = nestedFileData; this.substitutionNodeTemplate = substitutionNodeTemplate; @@ -72,45 +70,33 @@ abstract class BaseResourceConnection<T> { abstract List<Predicate<T>> getPredicatesListForConnectionPoints(); - abstract Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + abstract Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName); abstract String getDesiredResourceType(); - abstract String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, - Map.Entry<String, T> connectionPointEntry); + abstract String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, Map.Entry<String, T> connectionPointEntry); - abstract Map.Entry<String, T> getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, - Map.Entry<String, T> - connectionPointEntry); + abstract Map.Entry<String, T> getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, Map.Entry<String, T> connectionPointEntry); - abstract void addRequirementToConnectResources(Map.Entry<String, T> connectionPointEntry, - List<String> paramNames); + abstract void addRequirementToConnectResources(Map.Entry<String, T> connectionPointEntry, List<String> paramNames); abstract List<Map<String, T>> getAllConnectionPoints(); - abstract boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List<String> supportedTypes); + abstract boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List<String> supportedTypes); void connect() { - ServiceTemplate nestedServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()); + ServiceTemplate nestedServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates().get(translateTo.getResource().getType()); List<String> paramNames; HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(translateTo.getContext().getFileContentAsStream(nestedFileData.getFile()), - HeatOrchestrationTemplate.class); + .yamlToObject(translateTo.getContext().getFileContentAsStream(nestedFileData.getFile()), HeatOrchestrationTemplate.class); List<Map<String, T>> exposedConnectionPoints = getAllConnectionPoints(); for (Map<String, T> connectionPointsMap : exposedConnectionPoints) { for (Map.Entry<String, T> connectionPointEntry : connectionPointsMap.entrySet()) { - paramNames = - getConnectionParameterName(nestedServiceTemplate, nestedHeatOrchestrationTemplate, - nestedFileData.getFile(), connectionPointEntry); + paramNames = getConnectionParameterName(nestedServiceTemplate, nestedHeatOrchestrationTemplate, nestedFileData.getFile(), + connectionPointEntry); if (CollectionUtils.isNotEmpty(paramNames)) { addRequirementToConnectResources(connectionPointEntry, paramNames); } @@ -118,51 +104,38 @@ abstract class BaseResourceConnection<T> { } } - private List<String> getConnectionParameterName(ServiceTemplate nestedServiceTemplate, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, - String nestedHeatFileName, - Map.Entry<String, T> connectionPointEntry) { + private List<String> getConnectionParameterName(ServiceTemplate nestedServiceTemplate, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, + String nestedHeatFileName, Map.Entry<String, T> connectionPointEntry) { List<String> connectionParameterNameList = new ArrayList<>(); - String mappedTranslatedResourceId = getMappedNodeTranslatedResourceId(nestedServiceTemplate, - connectionPointEntry); - NodeTemplate mappedNodeTemplate = nestedServiceTemplate.getTopology_template().getNode_templates() - .get(mappedTranslatedResourceId); + String mappedTranslatedResourceId = getMappedNodeTranslatedResourceId(nestedServiceTemplate, connectionPointEntry); + NodeTemplate mappedNodeTemplate = nestedServiceTemplate.getTopology_template().getNode_templates().get(mappedTranslatedResourceId); if (isDesiredNodeTemplateType(mappedNodeTemplate)) { - return getResourcesConnectionParameterName(mappedTranslatedResourceId, - nestedHeatOrchestrationTemplate, nestedHeatFileName); + return getResourcesConnectionParameterName(mappedTranslatedResourceId, nestedHeatOrchestrationTemplate, nestedHeatFileName); } - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); if (!toscaAnalyzerService.isSubstitutableNodeTemplate(mappedNodeTemplate)) { return Collections.emptyList(); } Optional<String> mappedSubstituteServiceTemplateName = toscaAnalyzerService - .getSubstituteServiceTemplateName(mappedTranslatedResourceId, mappedNodeTemplate); + .getSubstituteServiceTemplateName(mappedTranslatedResourceId, mappedNodeTemplate); if (!mappedSubstituteServiceTemplateName.isPresent()) { return Collections.emptyList(); } - String mappedNestedHeatFileName = translateTo.getContext().getNestedHeatFileName() - .get(mappedSubstituteServiceTemplateName.get()); + String mappedNestedHeatFileName = translateTo.getContext().getNestedHeatFileName().get(mappedSubstituteServiceTemplateName.get()); if (Objects.isNull(mappedNestedHeatFileName)) { return Collections.emptyList(); } HeatOrchestrationTemplate mappedNestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(translateTo.getContext().getFileContentAsStream(mappedNestedHeatFileName), - HeatOrchestrationTemplate.class); - ServiceTemplate mappedNestedServiceTemplate = - translateTo.getContext().getTranslatedServiceTemplates().get(mappedNestedHeatFileName); - List<String> nestedPropertyNames = getConnectionParameterName(mappedNestedServiceTemplate, - mappedNestedHeatOrchestrationTemplate, mappedNestedHeatFileName, - getMappedConnectionPointEntry(nestedServiceTemplate, connectionPointEntry)); - + .yamlToObject(translateTo.getContext().getFileContentAsStream(mappedNestedHeatFileName), HeatOrchestrationTemplate.class); + ServiceTemplate mappedNestedServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates().get(mappedNestedHeatFileName); + List<String> nestedPropertyNames = getConnectionParameterName(mappedNestedServiceTemplate, mappedNestedHeatOrchestrationTemplate, + mappedNestedHeatFileName, getMappedConnectionPointEntry(nestedServiceTemplate, connectionPointEntry)); if (CollectionUtils.isEmpty(nestedPropertyNames)) { return connectionParameterNameList; } for (String propertyName : nestedPropertyNames) { Object propertyValue = mappedNodeTemplate.getProperties().get(propertyName); - if (propertyValue instanceof Map - && ((Map) propertyValue).containsKey(ToscaFunctions.GET_INPUT.getFunctionName())) { + if (propertyValue instanceof Map && ((Map) propertyValue).containsKey(ToscaFunctions.GET_INPUT.getFunctionName())) { Object paramName = ((Map) propertyValue).get(ToscaFunctions.GET_INPUT.getFunctionName()); if (paramName instanceof String) { connectionParameterNameList.add((String) paramName); @@ -172,46 +145,39 @@ abstract class BaseResourceConnection<T> { return connectionParameterNameList; } - private List<String> getResourcesConnectionParameterName(String translatedResourceId, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + private List<String> getResourcesConnectionParameterName(String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { List<String> params = new ArrayList<>(); - Optional<List<Map.Entry<String, Resource>>> heatResources = - getResourceByTranslatedResourceId(translatedResourceId, nestedHeatOrchestrationTemplate); + Optional<List<Map.Entry<String, Resource>>> heatResources = getResourceByTranslatedResourceId(translatedResourceId, + nestedHeatOrchestrationTemplate); if (!heatResources.isPresent()) { return params; } for (Map.Entry<String, Resource> resourceEntry : heatResources.get()) { Resource heatResource = resourceEntry.getValue(); if (!MapUtils.isEmpty(heatResource.getProperties())) { - Optional<List<String>> connectorParamName = - getConnectorPropertyParamName(resourceEntry.getKey(), heatResource, - nestedHeatOrchestrationTemplate, nestedHeatFileName); + Optional<List<String>> connectorParamName = getConnectorPropertyParamName(resourceEntry.getKey(), heatResource, + nestedHeatOrchestrationTemplate, nestedHeatFileName); connectorParamName.ifPresent(params::addAll); } } return params; } - protected Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId( - String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { - Optional<List<Map.Entry<String, Resource>>> resourceByTranslatedResourceId = - resourceTranslationBase.getResourceByTranslatedResourceId(nestedFileData.getFile(), - nestedHeatOrchestrationTemplate, translatedResourceId, translateTo, - getDesiredResourceType()); + protected Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId(String translatedResourceId, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { + Optional<List<Map.Entry<String, Resource>>> resourceByTranslatedResourceId = resourceTranslationBase + .getResourceByTranslatedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translatedResourceId, translateTo, + getDesiredResourceType()); if (!resourceByTranslatedResourceId.isPresent()) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage( - "Failed to get original resource from heat for translate resource id '" - + translatedResourceId + "'") - .withId(TranslatorErrorCodes.HEAT_TO_TOSCA_MAPPING_COLLISION) - .withCategory(ErrorCategory.APPLICATION).build()); + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage("Failed to get original resource from heat for translate resource id '" + translatedResourceId + "'") + .withId(TranslatorErrorCodes.HEAT_TO_TOSCA_MAPPING_COLLISION).withCategory(ErrorCategory.APPLICATION).build()); } return resourceByTranslatedResourceId; } - RequirementAssignment createRequirementAssignment(Map.Entry<String, RequirementDefinition> requirementEntry, - String node, + RequirementAssignment createRequirementAssignment(Map.Entry<String, RequirementDefinition> requirementEntry, String node, NodeTemplate nodeTemplate) { RequirementAssignment requirementAssignment = null; if (Objects.nonNull(node)) { @@ -224,88 +190,66 @@ abstract class BaseResourceConnection<T> { return requirementAssignment; } - - Optional<String> getConnectionTranslatedNodeUsingGetParamFunc( - Map.Entry<String, T> connectionPointEntry, String paramName, - List<String> supportedNodeTypes) { - - Optional<AttachedResourceId> attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); + Optional<String> getConnectionTranslatedNodeUsingGetParamFunc(Map.Entry<String, T> connectionPointEntry, String paramName, + List<String> supportedNodeTypes) { + Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); if (!attachedResourceId.isPresent()) { return Optional.empty(); } AttachedResourceId resourceId = attachedResourceId.get(); if (resourceId.isGetParam() && resourceId.getEntityId() instanceof String) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); - if (isSupportedSharedResource(paramName, connectionPointEntry.getKey(), supportedNodeTypes, - shareResource)) { + TranslatedHeatResource shareResource = translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); + if (isSupportedSharedResource(paramName, connectionPointEntry.getKey(), supportedNodeTypes, shareResource)) { return Optional.of(shareResource.getTranslatedId()); } } return Optional.empty(); } - private boolean isSupportedSharedResource(String paramName, String connectionPointId, - List<String> supportedNodeTypes, + private boolean isSupportedSharedResource(String paramName, String connectionPointId, List<String> supportedNodeTypes, TranslatedHeatResource shareResource) { - return Objects.nonNull(shareResource) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName()) - && validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, - connectionPointId, shareResource.getHeatResource(), supportedNodeTypes); + return Objects.nonNull(shareResource) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName()) + && validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, connectionPointId, shareResource.getHeatResource(), + supportedNodeTypes); } - Optional<TranslatedHeatResource> getConnectionTranslatedHeatResourceUsingGetParamFunc( - Map.Entry<String, T> connectionPointEntry, String paramName, - List<String> supportedNodeTypes) { - - Optional<AttachedResourceId> attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); + Optional<TranslatedHeatResource> getConnectionTranslatedHeatResourceUsingGetParamFunc(Map.Entry<String, T> connectionPointEntry, String paramName, + List<String> supportedNodeTypes) { + Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); if (!attachedResourceId.isPresent()) { return Optional.empty(); } AttachedResourceId resourceId = attachedResourceId.get(); if (resourceId.isGetParam() && resourceId.getEntityId() instanceof String) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); - if (isSupportedSharedResource(paramName, connectionPointEntry.getKey(), supportedNodeTypes, - shareResource)) { + TranslatedHeatResource shareResource = translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); + if (isSupportedSharedResource(paramName, connectionPointEntry.getKey(), supportedNodeTypes, shareResource)) { return Optional.of(shareResource); } } return Optional.empty(); } - - Optional<String> getConnectionTranslatedNodeUsingGetResourceFunc( - Map.Entry<String, T> connectionPointEntry, String paramName, Object paramValue, - List<String> supportedNodeTypes) { - Optional<String> getResourceAttachedResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); + Optional<String> getConnectionTranslatedNodeUsingGetResourceFunc(Map.Entry<String, T> connectionPointEntry, String paramName, Object paramValue, + List<String> supportedNodeTypes) { + Optional<String> getResourceAttachedResourceId = HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); if (getResourceAttachedResourceId.isPresent()) { // get resource - Resource resource = translateTo.getHeatOrchestrationTemplate().getResources() - .get(getResourceAttachedResourceId.get()); - if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, - connectionPointEntry.getKey(), resource, supportedNodeTypes)) { - return ResourceTranslationBase.getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), getResourceAttachedResourceId.get(), - translateTo.getContext()); + Resource resource = translateTo.getHeatOrchestrationTemplate().getResources().get(getResourceAttachedResourceId.get()); + if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, connectionPointEntry.getKey(), resource, + supportedNodeTypes)) { + return ResourceTranslationBase.getResourceTranslatedId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), + getResourceAttachedResourceId.get(), translateTo.getContext()); } } - return Optional.empty(); } - Optional<String> getConnectionResourceUsingGetResourceFunc( - Map.Entry<String, T> connectionPointEntry, String paramName, Object paramValue, - List<String> supportedNodeTypes) { - Optional<String> getResourceAttachedResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); + Optional<String> getConnectionResourceUsingGetResourceFunc(Map.Entry<String, T> connectionPointEntry, String paramName, Object paramValue, + List<String> supportedNodeTypes) { + Optional<String> getResourceAttachedResourceId = HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); if (getResourceAttachedResourceId.isPresent()) { // get resource - Resource resource = translateTo.getHeatOrchestrationTemplate().getResources() - .get(getResourceAttachedResourceId.get()); - if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, - connectionPointEntry.getKey(), resource, supportedNodeTypes)) { + Resource resource = translateTo.getHeatOrchestrationTemplate().getResources().get(getResourceAttachedResourceId.get()); + if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, connectionPointEntry.getKey(), resource, + supportedNodeTypes)) { return getResourceAttachedResourceId; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java index f7aa72cdb4..83824a3535 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java @@ -13,10 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION; + import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; @@ -35,49 +41,32 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Predicate; - -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION; - public class ContrailPortToNetResourceConnection extends ResourceConnectionUsingRequirementHelper { - ContrailPortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { + + ContrailPortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @Override protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - ToscaServiceModel toscaServiceModel = - HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); - return toscaAnalyzerService - .isTypeOf(nodeTemplate, ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, - translateTo.getContext().getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()), toscaServiceModel); + ToscaServiceModel toscaServiceModel = HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); + return toscaAnalyzerService.isTypeOf(nodeTemplate, ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, + translateTo.getContext().getTranslatedServiceTemplates().get(translateTo.getResource().getType()), toscaServiceModel); } @Override protected List<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { ArrayList<Predicate<RequirementDefinition>> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) - && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NATIVE_ROOT)) - && req.getRelationship() - .equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); + predicates.add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) && (req.getNode() == null || req.getNode() + .equals(ToscaNodeType.NATIVE_ROOT)) && req.getRelationship().equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); return predicates; } @Override - protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { Object interfaceListProperty = heatResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); if (interfaceListProperty == null) { @@ -85,25 +74,24 @@ public class ContrailPortToNetResourceConnection extends ResourceConnectionUsing } List<String> paramsList = new ArrayList<>(); if (interfaceListProperty instanceof List) { - return getConnectorPropertyParamNameFromList(nestedHeatOrchestrationTemplate, nestedHeatFileName, - (List) interfaceListProperty, paramsList); + return getConnectorPropertyParamNameFromList(nestedHeatOrchestrationTemplate, nestedHeatFileName, (List) interfaceListProperty, + paramsList); } else if (interfaceListProperty instanceof Map) { - return getConnectorPropertyParamNameFromMap(nestedHeatOrchestrationTemplate, nestedHeatFileName, - (Map) interfaceListProperty, paramsList); + return getConnectorPropertyParamNameFromMap(nestedHeatOrchestrationTemplate, nestedHeatFileName, (Map) interfaceListProperty, paramsList); } return Optional.empty(); } - private Optional<List<String>> getConnectorPropertyParamNameFromList( - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName, - List interfaceListProperty, List<String> paramsList) { + private Optional<List<String>> getConnectorPropertyParamNameFromList(HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, + String nestedHeatFileName, List interfaceListProperty, + List<String> paramsList) { for (Object interfaceEntry : interfaceListProperty) { if (interfaceEntry instanceof Map) { - Optional<AttachedResourceId> attachedVirtualNetwork = HeatToToscaUtil.extractAttachedResourceId( - nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), + Optional<AttachedResourceId> attachedVirtualNetwork = HeatToToscaUtil + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), ((Map) interfaceEntry).get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME)); - if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() - && attachedVirtualNetwork.get().getEntityId() instanceof String) { + if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() && attachedVirtualNetwork.get() + .getEntityId() instanceof String) { paramsList.add((String) attachedVirtualNetwork.get().getEntityId()); } } @@ -111,17 +99,14 @@ public class ContrailPortToNetResourceConnection extends ResourceConnectionUsing return Optional.of(paramsList); } - private Optional<List<String>> getConnectorPropertyParamNameFromMap(HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, - String nestedHeatFileName, - Map interfaceListProperty, + private Optional<List<String>> getConnectorPropertyParamNameFromMap(HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, + String nestedHeatFileName, Map interfaceListProperty, List<String> paramsList) { Optional<AttachedResourceId> attachedVirtualNetwork = HeatToToscaUtil - .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, - translateTo.getContext(), - interfaceListProperty.get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME)); - if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() - && attachedVirtualNetwork.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), + interfaceListProperty.get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME)); + if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() && attachedVirtualNetwork.get() + .getEntityId() instanceof String) { paramsList.add((String) attachedVirtualNetwork.get().getEntityId()); return Optional.of(paramsList); } @@ -134,40 +119,30 @@ public class ContrailPortToNetResourceConnection extends ResourceConnectionUsing } @Override - protected void addRequirementToConnectResources( - Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, - List<String> paramNames) { + protected void addRequirementToConnectResources(Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, List<String> paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } - Integer index = Integer.valueOf( - requirementDefinitionEntry.getKey().substring("link_port_".length()).substring(0, 1)); - + Integer index = Integer.valueOf(requirementDefinitionEntry.getKey().substring("link_port_".length()).substring(0, 1)); String paramName = paramNames.get( - index); // port can connect to one network only and we are + index); // port can connect to one network only and we are + // expecting to get only one param(unlike security rules to port) Object paramValue = translateTo.getResource().getProperties().get(paramName); - List<String> supportedNetworkTypes = - ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedNetworkTypes); + List<String> supportedNetworkTypes = ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedNetworkTypes); } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List<String> supportedTypes) { + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List<String> supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, - nestedPropertyName, connectedResource.getType(), connectionPointId, supportedTypes.toString()); + logger + .warn(LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } return true; } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java index 24ff55de60..a5ac194290 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_INTERFACE_VALUES_NESTED; @@ -26,7 +25,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; - import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; @@ -43,11 +41,9 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper; -public class ContrailV2VlanToInterfaceResourceConnection - extends ResourceConnectionUsingRequirementHelper { +public class ContrailV2VlanToInterfaceResourceConnection extends ResourceConnectionUsingRequirementHelper { - ContrailV2VlanToInterfaceResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, + ContrailV2VlanToInterfaceResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @@ -60,38 +56,29 @@ public class ContrailV2VlanToInterfaceResourceConnection @Override protected List<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { ArrayList<Predicate<RequirementDefinition>> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE) - && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NETWORK_PORT)) - && req.getRelationship() - .equals(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO)); + predicates.add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE) && (req.getNode() == null || req.getNode() + .equals(ToscaNodeType.NETWORK_PORT)) && req.getRelationship().equals(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO)); return predicates; } @Override - protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { List<String> interfaces = new ArrayList<>(); Object interfaceRefs = heatResource.getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); - if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) - || ((List) interfaceRefs).isEmpty()) { + if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) || ((List) interfaceRefs).isEmpty()) { return Optional.empty(); } if (((List) interfaceRefs).size() > 1) { - logger.warn(LOG_MULTIPLE_INTERFACE_VALUES_NESTED, - translateTo.getResourceId(), translateTo.getResource().getType(), heatResourceId, - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(), - HeatConstants.VMI_REFS_PROPERTY_NAME); + logger.warn(LOG_MULTIPLE_INTERFACE_VALUES_NESTED, translateTo.getResourceId(), translateTo.getResource().getType(), heatResourceId, + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(), HeatConstants.VMI_REFS_PROPERTY_NAME); } Object interfaceRef = ((List) interfaceRefs).get(0); Optional<AttachedResourceId> attachedInterfaceResource = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), interfaceRef); - if (attachedInterfaceResource.isPresent() && attachedInterfaceResource.get().isGetParam() - && attachedInterfaceResource.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translateTo.getContext(), interfaceRef); + if (attachedInterfaceResource.isPresent() && attachedInterfaceResource.get().isGetParam() && attachedInterfaceResource.get() + .getEntityId() instanceof String) { interfaces.add((String) attachedInterfaceResource.get().getEntityId()); } return Optional.of(interfaces); @@ -103,44 +90,32 @@ public class ContrailV2VlanToInterfaceResourceConnection } @Override - protected void addRequirementToConnectResources( - Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, - List<String> paramNames) { + protected void addRequirementToConnectResources(Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, List<String> paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } for (String paramName : paramNames) { Object paramValue = translateTo.getResource().getProperties().get(paramName); - List<String> supportedInterfaceTypes = - Arrays.asList(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE - .getHeatResource()); - - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedInterfaceTypes); + List<String> supportedInterfaceTypes = Arrays.asList(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedInterfaceTypes); } } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List<String> supportedTypes) { - if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes) - || (new ContrailV2VirtualMachineInterfaceHelper() - .isVlanSubInterfaceResource(connectedResource))) { - logger.warn(LOG_UNSUPPORTED_VMI_VLAN_SUB_INTERFACE_REQUIREMENT_CONNECTION, nestedResourceId, - nestedPropertyName, - getLogMessageSuffixForConnectedResource(connectedResource), connectedResource.getType(), - connectionPointId, supportedTypes.toString()); + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List<String> supportedTypes) { + if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes) || (new ContrailV2VirtualMachineInterfaceHelper() + .isVlanSubInterfaceResource(connectedResource))) { + logger.warn(LOG_UNSUPPORTED_VMI_VLAN_SUB_INTERFACE_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, + getLogMessageSuffixForConnectedResource(connectedResource), connectedResource.getType(), connectionPointId, + supportedTypes.toString()); return false; } return true; } private String getLogMessageSuffixForConnectedResource(Resource connectedResource) { - return new ContrailV2VirtualMachineInterfaceHelper() - .isVlanSubInterfaceResource(connectedResource) ? "Vlan Sub interface " : ""; + return new ContrailV2VirtualMachineInterfaceHelper().isVlanSubInterfaceResource(connectedResource) ? "Vlan Sub interface " : ""; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java index aece1b3d33..ed5b5928fe 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java @@ -13,10 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION; + import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; @@ -32,63 +40,44 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import java.util.*; -import java.util.function.Predicate; +public class ContrailV2VmInterfaceToNetResourceConnection extends ResourceConnectionUsingRequirementHelper { -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION; - -public class ContrailV2VmInterfaceToNetResourceConnection - extends ResourceConnectionUsingRequirementHelper { - - ContrailV2VmInterfaceToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, + ContrailV2VmInterfaceToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @Override protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { - return (nodeTemplate.getType() - .equals(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE) - || nodeTemplate.getType() - .equals(ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE)); + return (nodeTemplate.getType().equals(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE) || nodeTemplate.getType() + .equals(ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE)); } @Override protected List<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { ArrayList<Predicate<RequirementDefinition>> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) - && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NATIVE_ROOT)) - && req.getRelationship() - .equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); + predicates.add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) && (req.getNode() == null || req.getNode() + .equals(ToscaNodeType.NATIVE_ROOT)) && req.getRelationship().equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); return predicates; } @Override - protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { List<String> networks = new ArrayList<>(); Object virtualNetworkRefs = heatResource.getProperties().get(HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME); - if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) - || ((List) virtualNetworkRefs).isEmpty()) { + if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) || ((List) virtualNetworkRefs).isEmpty()) { return Optional.empty(); } if (((List) virtualNetworkRefs).size() > 1) { - logger.warn(LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES, translateTo.getResourceId(), - translateTo.getResource().getType(), heatResourceId, - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); + logger.warn(LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES, translateTo.getResourceId(), translateTo.getResource().getType(), heatResourceId, + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); } Object virtualNetworkRef = ((List) virtualNetworkRefs).get(0); Optional<AttachedResourceId> network = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), virtualNetworkRef); - if (network.isPresent() && network.get().isGetParam() - && network.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translateTo.getContext(), virtualNetworkRef); + if (network.isPresent() && network.get().isGetParam() && network.get().getEntityId() instanceof String) { networks.add((String) network.get().getEntityId()); } return Optional.of(networks); @@ -100,33 +89,24 @@ public class ContrailV2VmInterfaceToNetResourceConnection } @Override - protected void addRequirementToConnectResources( - Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, - List<String> paramNames) { + protected void addRequirementToConnectResources(Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, List<String> paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } for (String paramName : paramNames) { Object paramValue = translateTo.getResource().getProperties().get(paramName); - List<String> supportedNetworkTypes = - ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedNetworkTypes); + List<String> supportedNetworkTypes = ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedNetworkTypes); } } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List<String> supportedTypes) { + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List<String> supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION, - nestedResourceId, nestedPropertyName, connectedResource.getType(), connectionPointId, - supportedTypes.toString()); + logger.warn(LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } return true; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java index cd8e3764e2..e2a39e2bca 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VOL_ATTACHMENT_VOLUME_REQUIREMENT_CONNECTION; @@ -26,7 +25,6 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; @@ -53,8 +51,7 @@ import org.openecomp.sdc.translator.services.heattotosca.helper.VolumeTranslatio class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelper { - NovaToVolResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, + NovaToVolResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @@ -62,36 +59,27 @@ class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelp @Override boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - ToscaServiceModel toscaServiceModel = - HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); + ToscaServiceModel toscaServiceModel = HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); return toscaAnalyzerService.isTypeOf(nodeTemplate, ToscaNodeType.NOVA_SERVER, - translateTo.getContext().getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()), toscaServiceModel); + translateTo.getContext().getTranslatedServiceTemplates().get(translateTo.getResource().getType()), toscaServiceModel); } @Override List<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { ArrayList<Predicate<RequirementDefinition>> predicates = new ArrayList<>(); - predicates - .add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_ATTACHMENT) - && req.getNode().equals(ToscaNodeType.NATIVE_BLOCK_STORAGE) - && req.getRelationship() - .equals(ToscaRelationshipType.NATIVE_ATTACHES_TO)); + predicates.add( + req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_ATTACHMENT) && req.getNode().equals(ToscaNodeType.NATIVE_BLOCK_STORAGE) + && req.getRelationship().equals(ToscaRelationshipType.NATIVE_ATTACHES_TO)); return predicates; } @Override Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, - String nestedHeatFileName) { - - + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { Optional<AttachedResourceId> volumeId = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), heatResource.getProperties().get("volume_id")); - if (volumeId.isPresent() && volumeId.get().isGetParam() - && volumeId.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translateTo.getContext(), + heatResource.getProperties().get("volume_id")); + if (volumeId.isPresent() && volumeId.get().isGetParam() && volumeId.get().getEntityId() instanceof String) { return Optional.of(Collections.singletonList((String) volumeId.get().getEntityId())); } else { return Optional.empty(); @@ -104,58 +92,36 @@ class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelp } @Override - void addRequirementToConnectResources( - Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, - List<String> paramNames) { - - + void addRequirementToConnectResources(Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, List<String> paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } - - List<String> supportedVolumeTypes = - Collections.singletonList(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); - + List<String> supportedVolumeTypes = Collections.singletonList(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); for (String paramName : paramNames) { Object paramValue = translateTo.getResource().getProperties().get(paramName); - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedVolumeTypes); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedVolumeTypes); } - } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List<String> supportedTypes) { - - + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, String nestedPropertyName, String connectionPointId, + Resource connectedResource, List<String> supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_VOL_ATTACHMENT_VOLUME_REQUIREMENT_CONNECTION, nestedResourceId, - nestedPropertyName, connectedResource.getType(), connectionPointId, supportedTypes.toString()); + logger + .warn(LOG_UNSUPPORTED_VOL_ATTACHMENT_VOLUME_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } - return true; } @Override - protected Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId( - String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { - - - List<Predicate<Map.Entry<String, Resource>>> predicates = - buildPredicates(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translatedResourceId); - List<Map.Entry<String, Resource>> list = - nestedHeatOrchestrationTemplate.getResources().entrySet() - .stream() - .filter(entry -> predicates - .stream() - .allMatch(p -> p.test(entry))) - .collect(Collectors.toList()); + protected Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId(String translatedResourceId, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { + List<Predicate<Map.Entry<String, Resource>>> predicates = buildPredicates(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, + translatedResourceId); + List<Map.Entry<String, Resource>> list = nestedHeatOrchestrationTemplate.getResources().entrySet().stream() + .filter(entry -> predicates.stream().allMatch(p -> p.test(entry))).collect(Collectors.toList()); if (CollectionUtils.isEmpty(list)) { return Optional.empty(); } else { @@ -164,26 +130,20 @@ class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelp } @Override - Optional<String> getConnectionTranslatedNodeUsingGetParamFunc( - Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, String paramName, - List<String> supportedTargetNodeTypes) { - - + Optional<String> getConnectionTranslatedNodeUsingGetParamFunc(Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, + String paramName, List<String> supportedTargetNodeTypes) { Optional<String> targetTranslatedNodeId = super - .getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, - supportedTargetNodeTypes); + .getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, supportedTargetNodeTypes); if (targetTranslatedNodeId.isPresent()) { return targetTranslatedNodeId; } - Optional<AttachedResourceId> attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); + Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); if (!attachedResourceId.isPresent()) { return Optional.empty(); } AttachedResourceId resourceId = attachedResourceId.get(); if (resourceId.isGetParam() && resourceId.getEntityId() instanceof String) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); + TranslatedHeatResource shareResource = translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); if (Objects.nonNull(shareResource)) { return Optional.empty(); } @@ -191,36 +151,28 @@ class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelp Optional<FileData> fileData = HeatToToscaUtil.getFileData(translateTo.getHeatFileName(), allFilesData); if (fileData.isPresent()) { Optional<ResourceFileDataAndIDs> fileDataContainingResource = new VolumeTranslationHelper(logger) - .getFileDataContainingVolume(fileData.get().getData(), - (String) resourceId.getEntityId(), translateTo, FileData.Type.HEAT_VOL); + .getFileDataContainingVolume(fileData.get().getData(), (String) resourceId.getEntityId(), translateTo, FileData.Type.HEAT_VOL); if (fileDataContainingResource.isPresent()) { return Optional.of(fileDataContainingResource.get().getTranslatedResourceId()); } } } - return Optional.empty(); } - private List<Predicate<Map.Entry<String, Resource>>> buildPredicates( - String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String novaTranslatedResourceId) { + private List<Predicate<Map.Entry<String, Resource>>> buildPredicates(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + String novaTranslatedResourceId) { List<Predicate<Map.Entry<String, Resource>>> list = new ArrayList<>(); list.add(entry -> entry.getValue().getType().equals(getDesiredResourceType())); list.add(entry -> { Object instanceUuidProp = entry.getValue().getProperties().get("instance_uuid"); TranslationContext context = translateTo.getContext(); Optional<AttachedResourceId> instanceUuid = HeatToToscaUtil - .extractAttachedResourceId(fileName, heatOrchestrationTemplate, context, - instanceUuidProp); + .extractAttachedResourceId(fileName, heatOrchestrationTemplate, context, instanceUuidProp); if (instanceUuid.isPresent()) { - Optional<String> resourceTranslatedId = - ResourceTranslationBase.getResourceTranslatedId(fileName, heatOrchestrationTemplate, - (String) instanceUuid.get().getTranslatedId(), context); - return resourceTranslatedId.isPresent() - && resourceTranslatedId.get().equals(novaTranslatedResourceId); - + Optional<String> resourceTranslatedId = ResourceTranslationBase + .getResourceTranslatedId(fileName, heatOrchestrationTemplate, (String) instanceUuid.get().getTranslatedId(), context); + return resourceTranslatedId.isPresent() && resourceTranslatedId.get().equals(novaTranslatedResourceId); } else { throw new CoreException(new MissingMandatoryPropertyErrorBuilder("instance_uuid").build()); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java index 6782561b36..c3298a6ad5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_PORT_NETWORK_REQUIREMENT_CONNECTION; +import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; - import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; @@ -40,12 +39,9 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import com.google.common.collect.ImmutableList; - public class PortToNetResourceConnection extends ResourceConnectionUsingRequirementHelper { - PortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, + PortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @@ -58,33 +54,24 @@ public class PortToNetResourceConnection extends ResourceConnectionUsingRequirem @Override protected List<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { ArrayList<Predicate<RequirementDefinition>> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) - && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NATIVE_ROOT)) - && req.getRelationship().equals( - ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); + predicates.add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) && (req.getNode() == null || req.getNode() + .equals(ToscaNodeType.NATIVE_ROOT)) && req.getRelationship().equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); return predicates; } @Override - protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { Optional<AttachedResourceId> network = HeatToToscaUtil - .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo - .getContext(), heatResource.getProperties().get(HeatConstants.NETWORK_PROPERTY_NAME)); - if (network.isPresent() && network.get().isGetParam() - && network.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), + heatResource.getProperties().get(HeatConstants.NETWORK_PROPERTY_NAME)); + if (network.isPresent() && network.get().isGetParam() && network.get().getEntityId() instanceof String) { return Optional.of(Collections.singletonList((String) network.get().getEntityId())); } else { - network = HeatToToscaUtil - .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo - .getContext(), heatResource.getProperties().get(HeatConstants.NETWORK_ID_PROPERTY_NAME)); - if (network.isPresent() - && network.get().isGetParam() - && network.get().getEntityId() instanceof String) { + network = HeatToToscaUtil.extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), + heatResource.getProperties().get(HeatConstants.NETWORK_ID_PROPERTY_NAME)); + if (network.isPresent() && network.get().isGetParam() && network.get().getEntityId() instanceof String) { return Optional.of(Collections.singletonList((String) network.get().getEntityId())); } else { return Optional.empty(); @@ -98,37 +85,28 @@ public class PortToNetResourceConnection extends ResourceConnectionUsingRequirem } @Override - protected void addRequirementToConnectResources( - Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, - List<String> paramNames) { + protected void addRequirementToConnectResources(Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, List<String> paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } String paramName = paramNames.get(0); // port can connect to one network only and we are + // expecting to have only one param(unlike security rules to port) Object paramValue = translateTo.getResource().getProperties().get(paramName); - List<String> supportedNetworkTypes = ImmutableList.of( - HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedNetworkTypes); + List<String> supportedNetworkTypes = ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedNetworkTypes); } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List<String> supportedTypes) { + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List<String> supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_PORT_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, - nestedPropertyName, connectedResource.getType(), connectionPointId, supportedTypes.toString()); + logger.warn(LOG_UNSUPPORTED_PORT_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } return true; } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java index 0d89b0c363..c2284f29b5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED; @@ -25,8 +24,12 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; - -import org.onap.sdc.tosca.datatypes.model.*; +import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.onap.sdc.tosca.datatypes.model.NodeTemplate; +import org.onap.sdc.tosca.datatypes.model.NodeType; +import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; +import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.services.DataModelUtil; @@ -39,43 +42,31 @@ import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFact public abstract class ResourceConnectionUsingCapabilityHelper extends BaseResourceConnection<CapabilityDefinition> { - ResourceConnectionUsingCapabilityHelper(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { + ResourceConnectionUsingCapabilityHelper(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } - abstract Map.Entry<String, RequirementDefinition> createRequirementDefinition( - String capabilityKey); + abstract Map.Entry<String, RequirementDefinition> createRequirementDefinition(String capabilityKey); @Override - String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, - Map.Entry<String, - CapabilityDefinition> connectionPointEntry) { - List<String> substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() - .get(connectionPointEntry.getKey()); + String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, Map.Entry<String, CapabilityDefinition> connectionPointEntry) { + List<String> substitutionMapping = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() + .get(connectionPointEntry.getKey()); return substitutionMapping.get(0); } @Override - Map.Entry<String, CapabilityDefinition> getMappedConnectionPointEntry( - ServiceTemplate nestedServiceTemplate, - Map.Entry<String, CapabilityDefinition> connectionPointEntry) { - List<String> substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() - .get(connectionPointEntry.getKey()); + Map.Entry<String, CapabilityDefinition> getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, + Map.Entry<String, CapabilityDefinition> connectionPointEntry) { + List<String> substitutionMapping = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() + .get(connectionPointEntry.getKey()); String mappedNodeTranslatedId = substitutionMapping.get(0); String mappedCapabilityId = substitutionMapping.get(1); - NodeTemplate mappedNodeTemplate = - nestedServiceTemplate.getTopology_template().getNode_templates() - .get(mappedNodeTranslatedId); - NodeType substituteNodeType = - translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() - .get(mappedNodeTemplate.getType()); - Optional<CapabilityDefinition> capabilityDefinition = - DataModelUtil.getCapabilityDefinition(substituteNodeType, mappedCapabilityId); + NodeTemplate mappedNodeTemplate = nestedServiceTemplate.getTopology_template().getNode_templates().get(mappedNodeTranslatedId); + NodeType substituteNodeType = translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() + .get(mappedNodeTemplate.getType()); + Optional<CapabilityDefinition> capabilityDefinition = DataModelUtil.getCapabilityDefinition(substituteNodeType, mappedCapabilityId); return new Map.Entry<String, CapabilityDefinition>() { @Override public String getKey() { @@ -102,74 +93,53 @@ public abstract class ResourceConnectionUsingCapabilityHelper extends BaseResour if (capabilities == null) { return exposedRequirementsList; } - capabilities.entrySet() - .stream() - .filter(entry -> predicates - .stream() - .anyMatch(p -> p.test(entry.getValue()))) - .forEach(entry -> { - Map<String, CapabilityDefinition> exposedRequirementsMap = new HashMap<>(); - exposedRequirementsMap.put(entry.getKey(), entry.getValue()); - exposedRequirementsList.add(exposedRequirementsMap); - }); + capabilities.entrySet().stream().filter(entry -> predicates.stream().anyMatch(p -> p.test(entry.getValue()))).forEach(entry -> { + Map<String, CapabilityDefinition> exposedRequirementsMap = new HashMap<>(); + exposedRequirementsMap.put(entry.getKey(), entry.getValue()); + exposedRequirementsList.add(exposedRequirementsMap); + }); return exposedRequirementsList; } - void addRequirementToConnectResource(Map.Entry<String, CapabilityDefinition> connectionPointEntry, - List<String> supportedSourceNodeTypes, String paramName) { + void addRequirementToConnectResource(Map.Entry<String, CapabilityDefinition> connectionPointEntry, List<String> supportedSourceNodeTypes, + String paramName) { Object paramValue = translateTo.getResource().getProperties().get(paramName); if (paramValue == null) { - logger.warn(LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED, paramName, - translateTo.getResourceId(), connectionPointEntry.getKey(), ToscaConstants.CAPABILITY); + logger.warn(LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED, paramName, translateTo.getResourceId(), connectionPointEntry.getKey(), + ToscaConstants.CAPABILITY); return; } - - Map.Entry<String, RequirementDefinition> requirementDefinition = - createRequirementDefinition(connectionPointEntry.getKey()); - - Optional<String> sourceResourceId = - getConnectionResourceUsingGetResourceFunc(connectionPointEntry, paramName, paramValue, - supportedSourceNodeTypes); + Map.Entry<String, RequirementDefinition> requirementDefinition = createRequirementDefinition(connectionPointEntry.getKey()); + Optional<String> sourceResourceId = getConnectionResourceUsingGetResourceFunc(connectionPointEntry, paramName, paramValue, + supportedSourceNodeTypes); if (sourceResourceId.isPresent()) { Resource sourceResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), sourceResourceId.get(), - translateTo.getHeatFileName()); - Optional<String> translatedSourceNodeId = - ResourceTranslationFactory.getInstance(sourceResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), sourceResource, - sourceResourceId.get(), translateTo.getContext()); + .getResource(translateTo.getHeatOrchestrationTemplate(), sourceResourceId.get(), translateTo.getHeatFileName()); + Optional<String> translatedSourceNodeId = ResourceTranslationFactory.getInstance(sourceResource) + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + sourceResource, sourceResourceId.get(), translateTo.getContext()); if (translatedSourceNodeId.isPresent()) { - NodeTemplate sourceNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), translatedSourceNodeId.get()); - RequirementAssignment requirementAssignment = createRequirementAssignment( - requirementDefinition, translateTo.getTranslatedId(), sourceNodeTemplate); - ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), - translateTo.getResource(), sourceResource, translatedSourceNodeId.get(), - requirementDefinition.getKey(), requirementAssignment); + NodeTemplate sourceNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), translatedSourceNodeId.get()); + RequirementAssignment requirementAssignment = createRequirementAssignment(requirementDefinition, translateTo.getTranslatedId(), + sourceNodeTemplate); + ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), translateTo.getResource(), sourceResource, + translatedSourceNodeId.get(), requirementDefinition.getKey(), requirementAssignment); } else { - logger.warn(LOG_UNSUPPORTED_CAPABILITY_CONNECTION, sourceResource.getType(), - connectionPointEntry.getKey(), - connectionPointEntry.getValue().getType()); + logger.warn(LOG_UNSUPPORTED_CAPABILITY_CONNECTION, sourceResource.getType(), connectionPointEntry.getKey(), + connectionPointEntry.getValue().getType()); } } else { - Optional<TranslatedHeatResource> sharedSourceTranslatedHeatResource = - getConnectionTranslatedHeatResourceUsingGetParamFunc(connectionPointEntry, paramName, - supportedSourceNodeTypes); + Optional<TranslatedHeatResource> sharedSourceTranslatedHeatResource = getConnectionTranslatedHeatResourceUsingGetParamFunc( + connectionPointEntry, paramName, supportedSourceNodeTypes); if (sharedSourceTranslatedHeatResource.isPresent()) { NodeTemplate sharedSourceNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), - sharedSourceTranslatedHeatResource.get().getTranslatedId()); - RequirementAssignment requirementAssignment = createRequirementAssignment( - requirementDefinition, translateTo.getTranslatedId(), sharedSourceNodeTemplate); - - ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), - translateTo.getResource(), sharedSourceTranslatedHeatResource.get().getHeatResource(), - sharedSourceTranslatedHeatResource.get().getTranslatedId(), - requirementDefinition.getKey(), - requirementAssignment); + .getNodeTemplate(translateTo.getServiceTemplate(), sharedSourceTranslatedHeatResource.get().getTranslatedId()); + RequirementAssignment requirementAssignment = createRequirementAssignment(requirementDefinition, translateTo.getTranslatedId(), + sharedSourceNodeTemplate); + ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), translateTo.getResource(), + sharedSourceTranslatedHeatResource.get().getHeatResource(), sharedSourceTranslatedHeatResource.get().getTranslatedId(), + requirementDefinition.getKey(), requirementAssignment); } } } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java index a10eb348db..30ae5dd57a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED; @@ -24,52 +23,40 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; - import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; -//import org.openecomp.core.model.types.ServiceTemplate; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; abstract class ResourceConnectionUsingRequirementHelper extends BaseResourceConnection<RequirementDefinition> { - ResourceConnectionUsingRequirementHelper(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { + + ResourceConnectionUsingRequirementHelper(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @Override - String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, - Map.Entry<String, - RequirementDefinition> connectionPointEntry) { - List<String> substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() - .get(connectionPointEntry.getKey()); + String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, Map.Entry<String, RequirementDefinition> connectionPointEntry) { + List<String> substitutionMapping = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() + .get(connectionPointEntry.getKey()); return substitutionMapping.get(0); } @Override - Map.Entry<String, RequirementDefinition> getMappedConnectionPointEntry( - ServiceTemplate nestedServiceTemplate, - Map.Entry<String, RequirementDefinition> connectionPointEntry) { - List<String> substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() - .get(connectionPointEntry.getKey()); + Map.Entry<String, RequirementDefinition> getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, + Map.Entry<String, RequirementDefinition> connectionPointEntry) { + List<String> substitutionMapping = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() + .get(connectionPointEntry.getKey()); String mappedNodeTranslatedId = substitutionMapping.get(0); String mappedReqId = substitutionMapping.get(1); - NodeTemplate mappedNodeTemplate = - nestedServiceTemplate.getTopology_template().getNode_templates() - .get(mappedNodeTranslatedId); - NodeType substituteNodeType = - translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() - .get(mappedNodeTemplate.getType()); - Optional<RequirementDefinition> requirementDefinition = - DataModelUtil.getRequirementDefinition(substituteNodeType, mappedReqId); + NodeTemplate mappedNodeTemplate = nestedServiceTemplate.getTopology_template().getNode_templates().get(mappedNodeTranslatedId); + NodeType substituteNodeType = translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() + .get(mappedNodeTemplate.getType()); + Optional<RequirementDefinition> requirementDefinition = DataModelUtil.getRequirementDefinition(substituteNodeType, mappedReqId); return new Map.Entry<String, RequirementDefinition>() { @Override public String getKey() { @@ -96,41 +83,30 @@ abstract class ResourceConnectionUsingRequirementHelper extends BaseResourceConn if (requirements == null) { return exposedRequirementsList; } - requirements.stream() - .map(Map::entrySet) - .forEach(x -> x.stream() - .filter(entry -> predicates - .stream() - .anyMatch(p -> p.test(entry.getValue()))) - .forEach(entry -> { - Map<String, RequirementDefinition> exposedRequirementsMap = new HashMap<>(); - exposedRequirementsMap.put(entry.getKey(), entry.getValue()); - exposedRequirementsList.add(exposedRequirementsMap); - })); + requirements.stream().map(Map::entrySet) + .forEach(x -> x.stream().filter(entry -> predicates.stream().anyMatch(p -> p.test(entry.getValue()))).forEach(entry -> { + Map<String, RequirementDefinition> exposedRequirementsMap = new HashMap<>(); + exposedRequirementsMap.put(entry.getKey(), entry.getValue()); + exposedRequirementsList.add(exposedRequirementsMap); + })); return exposedRequirementsList; } - void addRequirementToConnectResource( - Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, String paramName, - Object paramValue, List<String> supportedNetworkTypes) { + void addRequirementToConnectResource(Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, String paramName, Object paramValue, + List<String> supportedNetworkTypes) { if (paramValue == null) { - logger.warn(LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED, paramName, translateTo.getResourceId(), - requirementDefinitionEntry.getKey(), ToscaConstants.REQUIREMENT); + logger.warn(LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED, paramName, translateTo.getResourceId(), requirementDefinitionEntry.getKey(), + ToscaConstants.REQUIREMENT); return; } - Optional<String> targetTranslatedNodeId = - getConnectionTranslatedNodeUsingGetResourceFunc(requirementDefinitionEntry, paramName, - paramValue, supportedNetworkTypes); + Optional<String> targetTranslatedNodeId = getConnectionTranslatedNodeUsingGetResourceFunc(requirementDefinitionEntry, paramName, paramValue, + supportedNetworkTypes); if (targetTranslatedNodeId.isPresent()) { - createRequirementAssignment(requirementDefinitionEntry, targetTranslatedNodeId.get(), - substitutionNodeTemplate); + createRequirementAssignment(requirementDefinitionEntry, targetTranslatedNodeId.get(), substitutionNodeTemplate); } else { - targetTranslatedNodeId = - getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, - supportedNetworkTypes); - targetTranslatedNodeId - .ifPresent(targetTranslatedId -> createRequirementAssignment(requirementDefinitionEntry, - targetTranslatedId, substitutionNodeTemplate)); + targetTranslatedNodeId = getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, supportedNetworkTypes); + targetTranslatedNodeId.ifPresent( + targetTranslatedId -> createRequirementAssignment(requirementDefinitionEntry, targetTranslatedId, substitutionNodeTemplate)); } } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java index 9011c9e91c..1e04028480 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import java.util.ArrayList; @@ -25,9 +24,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; - import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -62,76 +59,49 @@ public abstract class ResourceTranslationBase { * @param context the context * @return the resource translated id */ - public static Optional<String> getResourceTranslatedId(String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - String resourceId, - TranslationContext context) { + public static Optional<String> getResourceTranslatedId(String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceId, TranslationContext context) { if (!context.getTranslatedIds().containsKey(heatFileName)) { context.getTranslatedIds().put(heatFileName, new HashMap<>()); } - Map<String, String> translatedIdsPerFile = context.getTranslatedIds().get(heatFileName); String translatedId = translatedIdsPerFile.get(resourceId); if (translatedId != null) { return Optional.of(translatedId); } - Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { - throw new CoreException( - new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); + throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); } - return getTranslatedResourceId(resourceId, heatFileName, resource, heatOrchestrationTemplate, - context - ); + return getTranslatedResourceId(resourceId, heatFileName, resource, heatOrchestrationTemplate, context); } - private static Optional<String> getTranslatedResourceId(String resourceId, - String heatFileName, - Resource resource, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - TranslateTo translateTo = - generateTranslationTo(heatFileName, heatOrchestrationTemplate, resource, resourceId, - context); - - String translatedId = - ResourceTranslationFactory.getInstance(resource).generateTranslatedId(translateTo); - - if (ConsolidationDataUtil.isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(translatedId, - heatFileName, context)) { + private static Optional<String> getTranslatedResourceId(String resourceId, String heatFileName, Resource resource, + HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { + TranslateTo translateTo = generateTranslationTo(heatFileName, heatOrchestrationTemplate, resource, resourceId, context); + String translatedId = ResourceTranslationFactory.getInstance(resource).generateTranslatedId(translateTo); + if (ConsolidationDataUtil.isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(translatedId, heatFileName, context)) { return Optional.empty(); } - if (translatedId != null) { context.getTranslatedIds().get(heatFileName).put(resourceId, translatedId); } - return Optional.ofNullable(translatedId); } private static Optional<ToscaTopologyTemplateElements> getResourceTranslatedElementTemplate(String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String resourceId, TranslationContext context) { + HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceId, TranslationContext context) { Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { - throw new CoreException( - new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); + throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); } - TranslateTo translateTo = - generateTranslationTo(heatFileName, heatOrchestrationTemplate, resource, resourceId, - context); - - return ResourceTranslationFactory.getInstance(resource) - .getTranslatedToscaTopologyElement(translateTo); + TranslateTo translateTo = generateTranslationTo(heatFileName, heatOrchestrationTemplate, resource, resourceId, context); + return ResourceTranslationFactory.getInstance(resource).getTranslatedToscaTopologyElement(translateTo); } - private static TranslateTo generateTranslationTo(String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - Resource resource, String resourceId, - TranslationContext context) { + private static TranslateTo generateTranslationTo(String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, Resource resource, + String resourceId, TranslationContext context) { TranslateTo to = new TranslateTo(); to.setHeatFileName(heatFileName); to.setServiceTemplate(null); @@ -157,16 +127,12 @@ public abstract class ResourceTranslationBase { * @return the translated id if this resource is supported, or empty value if not supported */ public Optional<String> translateResource(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Resource resource, String resourceId, + HeatOrchestrationTemplate heatOrchestrationTemplate, Resource resource, String resourceId, TranslationContext context) { - Optional<String> translatedId = - getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); + Optional<String> translatedId = getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); context.getTranslatedResources().putIfAbsent(heatFileName, new HashSet<>()); - if (isResourceWithSameIdAppearsInOtherFiles(heatFileName, resourceId, context)) { - throw new CoreException( - new DuplicateResourceIdsInDifferentFilesErrorBuilder(resourceId).build()); + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(resourceId).build()); } if (context.getTranslatedResources().get(heatFileName).contains(resourceId)) { return translatedId; @@ -174,13 +140,11 @@ public abstract class ResourceTranslationBase { if (!translatedId.isPresent()) { return Optional.empty(); } - logger.debug("Translate- file: {} resource Id: {} translated resource id: {}", - heatFileName, resourceId, translatedId.get()); - TranslateTo translateTo = new TranslateTo(heatFileName, serviceTemplate, - heatOrchestrationTemplate, resource, resourceId, translatedId.get(), context); + logger.debug("Translate- file: {} resource Id: {} translated resource id: {}", heatFileName, resourceId, translatedId.get()); + TranslateTo translateTo = new TranslateTo(heatFileName, serviceTemplate, heatOrchestrationTemplate, resource, resourceId, translatedId.get(), + context); translate(translateTo); context.getTranslatedResources().get(heatFileName).add(resourceId); - if (DataModelUtil.isNodeTemplate(translatedId.get(), serviceTemplate)) { if (!context.getHeatStackGroupMembers().containsKey(heatFileName)) { context.getHeatStackGroupMembers().put(heatFileName, new HashSet<>()); @@ -191,14 +155,9 @@ public abstract class ResourceTranslationBase { return translatedId; } - private boolean isResourceWithSameIdAppearsInOtherFiles(String heatFileName, - String resourceId, - TranslationContext context) { - Set<String> translatedResourceIdsFromOtherFiles = - context.getTranslatedResourceIdsFromOtherFiles(heatFileName); - - return CollectionUtils.isNotEmpty(translatedResourceIdsFromOtherFiles) - && translatedResourceIdsFromOtherFiles.contains(resourceId); + private boolean isResourceWithSameIdAppearsInOtherFiles(String heatFileName, String resourceId, TranslationContext context) { + Set<String> translatedResourceIdsFromOtherFiles = context.getTranslatedResourceIdsFromOtherFiles(heatFileName); + return CollectionUtils.isNotEmpty(translatedResourceIdsFromOtherFiles) && translatedResourceIdsFromOtherFiles.contains(resourceId); } protected String generateTranslatedId(TranslateTo translateTo) { @@ -207,11 +166,9 @@ public abstract class ResourceTranslationBase { } else { return null; } - } - protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement(TranslateTo translateTo) { if (isEssentialRequirementsValid(translateTo)) { return Optional.of(ToscaTopologyTemplateElements.NODE_TEMPLATE); } else { @@ -224,12 +181,10 @@ public abstract class ResourceTranslationBase { } private void updateResourceDependency(TranslateTo translateTo) { - Resource resource = translateTo.getResource(); if (resource.getDepends_on() == null) { return; } - if (resource.getDepends_on() instanceof List) { List<String> dependsOnList = (List<String>) resource.getDepends_on(); for (String dependsOnResourceId : dependsOnList) { @@ -243,67 +198,47 @@ public abstract class ResourceTranslationBase { private void addDependency(String dependsOnResourceId, TranslateTo translateTo) { String heatFileName = translateTo.getHeatFileName(); - HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo - .getHeatOrchestrationTemplate(); + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo.getHeatOrchestrationTemplate(); TranslationContext context = translateTo.getContext(); - - Optional<String> resourceTranslatedId = - getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, dependsOnResourceId, - context); - - Optional<ToscaTopologyTemplateElements> resourceTranslatedElementTemplate = - getResourceTranslatedElementTemplate(heatFileName, heatOrchestrationTemplate, - dependsOnResourceId, context); - - if (resourceTranslatedId.isPresent() - && (resourceTranslatedElementTemplate.isPresent() - && resourceTranslatedElementTemplate.get() == ToscaTopologyTemplateElements.NODE_TEMPLATE)) { + Optional<String> resourceTranslatedId = getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, dependsOnResourceId, context); + Optional<ToscaTopologyTemplateElements> resourceTranslatedElementTemplate = getResourceTranslatedElementTemplate(heatFileName, + heatOrchestrationTemplate, dependsOnResourceId, context); + if (resourceTranslatedId.isPresent() && (resourceTranslatedElementTemplate.isPresent() + && resourceTranslatedElementTemplate.get() == ToscaTopologyTemplateElements.NODE_TEMPLATE)) { Resource sourceResource = translateTo.getResource(); - Resource targetResource = HeatToToscaUtil.getResource(heatOrchestrationTemplate, dependsOnResourceId, - translateTo.getHeatFileName()); + Resource targetResource = HeatToToscaUtil.getResource(heatOrchestrationTemplate, dependsOnResourceId, translateTo.getHeatFileName()); if (isValidDependency(sourceResource, targetResource, translateTo)) { - addDependsOnRequirement(dependsOnResourceId, translateTo, resourceTranslatedId.get(), sourceResource, - targetResource); + addDependsOnRequirement(dependsOnResourceId, translateTo, resourceTranslatedId.get(), sourceResource, targetResource); } } } - private void addDependsOnRequirement(String dependsOnResourceId, TranslateTo translateTo, - String resourceTranslatedId, Resource sourceResource, + private void addDependsOnRequirement(String dependsOnResourceId, TranslateTo translateTo, String resourceTranslatedId, Resource sourceResource, Resource targetResource) { RequirementAssignment requirementAssignment = new RequirementAssignment(); requirementAssignment.setNode(resourceTranslatedId); requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_NODE); requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_DEPENDS_ON); - DataModelUtil.addRequirementAssignment(translateTo.getServiceTemplate().getTopology_template() - .getNode_templates().get(translateTo.getTranslatedId()), + DataModelUtil + .addRequirementAssignment(translateTo.getServiceTemplate().getTopology_template().getNode_templates().get(translateTo.getTranslatedId()), ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, requirementAssignment); ConsolidationDataUtil - .updateNodesConnectedData(translateTo, dependsOnResourceId, targetResource, - sourceResource, translateTo.getTranslatedId(), ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, - requirementAssignment); + .updateNodesConnectedData(translateTo, dependsOnResourceId, targetResource, sourceResource, translateTo.getTranslatedId(), + ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, requirementAssignment); } private boolean isValidDependency(Resource sourceResource, Resource targetResource, TranslateTo translateTo) { - return !(HeatToToscaUtil.isNestedResource(sourceResource) || HeatToToscaUtil.isNestedResource(targetResource)) - && HeatToToscaUtil.isValidDependsOnCandidate(sourceResource, targetResource, - ConsolidationEntityType.OTHER, translateTo.getContext()); + return !(HeatToToscaUtil.isNestedResource(sourceResource) || HeatToToscaUtil.isNestedResource(targetResource)) && HeatToToscaUtil + .isValidDependsOnCandidate(sourceResource, targetResource, ConsolidationEntityType.OTHER, translateTo.getContext()); } - Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId( - String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId, - TranslateTo translateTo, - String heatResourceType) { - List<Map.Entry<String, Resource>> list = heatOrchestrationTemplate.getResources().entrySet() - .stream() - .filter(entry -> getPredicatesForTranslatedIdToResourceId(heatFileName, - heatOrchestrationTemplate, translatedResourceId, translateTo.getContext(), - heatResourceType) - .stream() - .allMatch(p -> p.test(entry))) - .collect(Collectors.toList()); + Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId(String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, TranslateTo translateTo, + String heatResourceType) { + List<Map.Entry<String, Resource>> list = heatOrchestrationTemplate.getResources().entrySet().stream().filter( + entry -> getPredicatesForTranslatedIdToResourceId(heatFileName, heatOrchestrationTemplate, translatedResourceId, translateTo.getContext(), + heatResourceType).stream().allMatch(p -> p.test(entry))).collect(Collectors.toList()); if (CollectionUtils.isEmpty(list)) { return Optional.empty(); } else { @@ -311,17 +246,16 @@ public abstract class ResourceTranslationBase { } } - private List<Predicate<Map.Entry<String, Resource>>> getPredicatesForTranslatedIdToResourceId( - String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId, TranslationContext context, String heatResourceType) { + private List<Predicate<Map.Entry<String, Resource>>> getPredicatesForTranslatedIdToResourceId(String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, + TranslationContext context, + String heatResourceType) { List<Predicate<Map.Entry<String, Resource>>> list = new ArrayList<>(); - list.add(entry -> - entry.getValue().getType().equals(heatResourceType)); + list.add(entry -> entry.getValue().getType().equals(heatResourceType)); list.add(entry -> { - Optional<String> resourceTranslatedId = - getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, entry.getKey(), context); - return resourceTranslatedId.isPresent() - && resourceTranslatedId.get().equals(translatedResourceId); + Optional<String> resourceTranslatedId = getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, entry.getKey(), context); + return resourceTranslatedId.isPresent() && resourceTranslatedId.get().equals(translatedResourceId); }); return list; } @@ -329,5 +263,4 @@ public abstract class ResourceTranslationBase { boolean isUnsupportedResourceType(Resource resource, List<String> supportedTypes) { return !Objects.nonNull(resource) || !supportedTypes.contains(resource.getType()); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java index ed772346cf..a0ec36c937 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_INSTANCE_UUID; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; + +import java.util.List; +import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.RelationshipTemplate; @@ -42,13 +47,6 @@ import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatory import org.openecomp.sdc.translator.services.heattotosca.helper.VolumeTranslationHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.List; -import java.util.Optional; - -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_INSTANCE_UUID; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; - public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTranslationBase { protected static Logger logger = LoggerFactory.getLogger(ResourceTranslationCinderVolumeAttachmentImpl.class); @@ -59,19 +57,15 @@ public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTrans relationTemplate.setType(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO); String heatFileName = translateTo.getHeatFileName(); relationTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - relationTemplate.getProperties(), heatFileName, - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - relationTemplate, translateTo.getContext())); - + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), relationTemplate.getProperties(), heatFileName, translateTo.getHeatOrchestrationTemplate(), + translateTo.getResource().getType(), relationTemplate, translateTo.getContext())); String volumeIdPropertyName = HeatConstants.VOL_ID_PROPERTY_NAME; AttachedResourceId attachedVolumeId = getAttachedResourceId(translateTo, volumeIdPropertyName); String instanceUuid = HeatConstants.INSTANCE_UUID_PROPERTY_NAME; AttachedResourceId attachedNovaServerId = getAttachedResourceId(translateTo, instanceUuid); if (attachedNovaServerId.isGetResource()) { - handleNovaGetResource(translateTo, relationTemplate, attachedVolumeId, - (String) attachedNovaServerId.getEntityId()); + handleNovaGetResource(translateTo, relationTemplate, attachedVolumeId, (String) attachedNovaServerId.getEntityId()); } else { logger.warn(LOG_INVALID_INSTANCE_UUID, translateTo.getResourceId(), translateTo.getResource().getType()); } @@ -87,16 +81,15 @@ public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTrans } private AttachedResourceId getAttachedResourceId(TranslateTo translateTo, String propertyName) { - Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, - propertyName); + Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); if (!attachedResourceId.isPresent()) { throw new CoreException(new MissingMandatoryPropertyErrorBuilder(propertyName).build()); } return attachedResourceId.get(); } - private void handleNovaGetResource(TranslateTo translateTo, RelationshipTemplate relationTemplate, - AttachedResourceId volResourceId, String novaResourceId) { + private void handleNovaGetResource(TranslateTo translateTo, RelationshipTemplate relationTemplate, AttachedResourceId volResourceId, + String novaResourceId) { RequirementAssignment requirement = new RequirementAssignment(); String toscaCapabilityAttachment = ToscaCapabilityType.NATIVE_ATTACHMENT; requirement.setCapability(toscaCapabilityAttachment); @@ -108,93 +101,72 @@ public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTrans translateNovaServerResource(translateTo, novaResourceId, requirement); } - private void translateNovaServerResource(TranslateTo translateTo, String novaResourceId, - RequirementAssignment requirement) { - Resource novaServerResource = - getResource(translateTo.getHeatOrchestrationTemplate(), novaResourceId, translateTo.getHeatFileName()); - if (!StringUtils.equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource(), - novaServerResource.getType())) { - logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), - novaServerResource.getType(), HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource()); + private void translateNovaServerResource(TranslateTo translateTo, String novaResourceId, RequirementAssignment requirement) { + Resource novaServerResource = getResource(translateTo.getHeatOrchestrationTemplate(), novaResourceId, translateTo.getHeatFileName()); + if (!StringUtils.equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource(), novaServerResource.getType())) { + logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), novaServerResource.getType(), + HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource()); return; } Optional<String> translatedNovaServerId = ResourceTranslationFactory.getInstance(novaServerResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), novaServerResource, novaResourceId, - translateTo.getContext()); - + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + novaServerResource, novaResourceId, translateTo.getContext()); if (translatedNovaServerId.isPresent() && StringUtils.isNotEmpty(requirement.getNode())) { - NodeTemplate novaServerNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), translatedNovaServerId.get()); - DataModelUtil.addRequirementAssignment(novaServerNodeTemplate, ToscaConstants - .LOCAL_STORAGE_REQUIREMENT_ID, requirement); + NodeTemplate novaServerNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), translatedNovaServerId.get()); + DataModelUtil.addRequirementAssignment(novaServerNodeTemplate, ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirement); //Add volume information to consolidation data - ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, - novaServerNodeTemplate.getType(), translatedNovaServerId.get(), ToscaConstants - .LOCAL_STORAGE_REQUIREMENT_ID, requirement); + ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, novaServerNodeTemplate.getType(), translatedNovaServerId.get(), + ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirement); } } - private void createVolumeNovaRelationshipForVolGetParam(TranslateTo translateTo, - RelationshipTemplate relationTemplate, - AttachedResourceId volResourceId, - RequirementAssignment requirement) { + private void createVolumeNovaRelationshipForVolGetParam(TranslateTo translateTo, RelationshipTemplate relationTemplate, + AttachedResourceId volResourceId, RequirementAssignment requirement) { String volumeResourceIdParamName = (String) volResourceId.getEntityId(); - if (translateTo.getContext().getHeatSharedResourcesByParam().containsKey(volumeResourceIdParamName) - && !isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + if (translateTo.getContext().getHeatSharedResourcesByParam().containsKey(volumeResourceIdParamName) && !isHeatFileNested(translateTo, + translateTo.getHeatFileName())) { handleSharedVolume(translateTo, relationTemplate, requirement, volumeResourceIdParamName); } else { handleUnsharedVolume(translateTo, relationTemplate, requirement, volumeResourceIdParamName); } } - private void handleSharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, - RequirementAssignment requirement, String volumeResourceIdParamName) { - Resource volServerResource = translateTo.getContext().getHeatSharedResourcesByParam() - .get(volumeResourceIdParamName).getHeatResource(); - if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - volServerResource.getType())) { - logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), - volServerResource.getType(), - HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); + private void handleSharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, RequirementAssignment requirement, + String volumeResourceIdParamName) { + Resource volServerResource = translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName).getHeatResource(); + if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), volServerResource.getType())) { + logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), volServerResource.getType(), + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); return; } - requirement.setNode(translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName) - .getTranslatedId()); + requirement.setNode(translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName).getTranslatedId()); requirement.setRelationship(translateTo.getTranslatedId()); - DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - relationTemplate); + DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), relationTemplate); } - private void createVolumeNovaRelationshipForVolGetResource(TranslateTo translateTo, - RelationshipTemplate relationTemplate, - AttachedResourceId volResourceId, - RequirementAssignment requirement) { - Resource volServerResource = getResource(translateTo.getHeatOrchestrationTemplate(), - (String) volResourceId.getTranslatedId(), translateTo.getHeatFileName()); - if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - volServerResource.getType())) { + private void createVolumeNovaRelationshipForVolGetResource(TranslateTo translateTo, RelationshipTemplate relationTemplate, + AttachedResourceId volResourceId, RequirementAssignment requirement) { + Resource volServerResource = getResource(translateTo.getHeatOrchestrationTemplate(), (String) volResourceId.getTranslatedId(), + translateTo.getHeatFileName()); + if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), volServerResource.getType())) { logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), volServerResource.getType(), - HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); return; } requirement.setNode((String) volResourceId.getTranslatedId()); requirement.setRelationship(translateTo.getTranslatedId()); - DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - relationTemplate); + DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), relationTemplate); } - private void handleUnsharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, - RequirementAssignment requirement, String volumeResourceId) { + private void handleUnsharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, RequirementAssignment requirement, + String volumeResourceId) { List<FileData> allFilesData = translateTo.getContext().getManifest().getContent().getData(); Optional<FileData> fileData = HeatToToscaUtil.getFileData(translateTo.getHeatFileName(), allFilesData); if (fileData.isPresent()) { - Optional<ResourceFileDataAndIDs> fileDataContainingResource = - new VolumeTranslationHelper(logger) - .getFileDataContainingVolume(fileData.get().getData(), volumeResourceId, translateTo, - FileData.Type.HEAT_VOL); - fileDataContainingResource.ifPresent(resourceFileDataAndIDs -> addRelationshipToServiceTemplate( - translateTo, relationTemplate, requirement, resourceFileDataAndIDs)); + Optional<ResourceFileDataAndIDs> fileDataContainingResource = new VolumeTranslationHelper(logger) + .getFileDataContainingVolume(fileData.get().getData(), volumeResourceId, translateTo, FileData.Type.HEAT_VOL); + fileDataContainingResource.ifPresent( + resourceFileDataAndIDs -> addRelationshipToServiceTemplate(translateTo, relationTemplate, requirement, resourceFileDataAndIDs)); } } @@ -202,17 +174,13 @@ public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTrans return translateTo.getContext().getNestedHeatsFiles().contains(heatFileName); } - private void addRelationshipToServiceTemplate(TranslateTo translateTo, - RelationshipTemplate relationTemplate, - RequirementAssignment requirement, + private void addRelationshipToServiceTemplate(TranslateTo translateTo, RelationshipTemplate relationTemplate, RequirementAssignment requirement, ResourceFileDataAndIDs resourceFileDataAndIDs) { String translatedId = resourceFileDataAndIDs.getTranslatedResourceId(); - String toscaVolIdPropName = - HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VOL_ID_PROPERTY_NAME); + String toscaVolIdPropName = HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VOL_ID_PROPERTY_NAME); relationTemplate.getProperties().put(toscaVolIdPropName, translatedId); requirement.setNode(translatedId); requirement.setRelationship(translateTo.getTranslatedId()); - DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - relationTemplate); + DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), relationTemplate); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java index a69c26c04f..a00d45e164 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import java.util.Map; @@ -26,7 +25,6 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - public class ResourceTranslationCinderVolumeImpl extends ResourceTranslationBase { private static final String VOLUME_SIZE_PROPERTY_NAME = "size"; @@ -36,23 +34,18 @@ public class ResourceTranslationCinderVolumeImpl extends ResourceTranslationBase final NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CINDER_VOLUME); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); handleSizeProperty(nodeTemplate.getProperties()); - final String toscaReadOnlyPropName = - HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.READ_ONLY_PROPERTY_NAME); + final String toscaReadOnlyPropName = HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.READ_ONLY_PROPERTY_NAME); final Object readOnlyPropVal = nodeTemplate.getProperties().get(toscaReadOnlyPropName); if (readOnlyPropVal != null && !(readOnlyPropVal instanceof Map)) { nodeTemplate.getProperties().put(toscaReadOnlyPropName, HeatBoolean.eval(readOnlyPropVal)); } - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } - private void handleSizeProperty(final Map<String, Object> nodeTemplateProperties) { final Object size = nodeTemplateProperties.get(VOLUME_SIZE_PROPERTY_NAME); if (size == null) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java index 5708748ce9..ede04e1ff0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java @@ -13,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.heat.services.HeatConstants.NETWORK_PROPERTY_NAME; +import static org.openecomp.sdc.tosca.services.DataModelUtil.createAttachmentRequirementAssignment; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_POLICY_RESOURCE; + +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.heat.datatypes.model.Resource; @@ -30,12 +36,6 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; -import java.util.Optional; - -import static org.openecomp.sdc.heat.services.HeatConstants.NETWORK_PROPERTY_NAME; -import static org.openecomp.sdc.tosca.services.DataModelUtil.createAttachmentRequirementAssignment; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.*; - public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTranslationBase { protected static Logger logger = LoggerFactory.getLogger(ResourceTranslationContrailAttachPolicyImpl.class); @@ -47,11 +47,10 @@ public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTransla if (translatedNetworkResourceId == null) { return; } - NodeTemplate policyNodeTemplate = getTranslatedPolicyNodeTemplate(translateTo, heatFileName); if (policyNodeTemplate != null) { DataModelUtil.addRequirementAssignment(policyNodeTemplate, ToscaConstants.NETWORK_REQUIREMENT_ID, - createAttachmentRequirementAssignment(translatedNetworkResourceId)); + createAttachmentRequirementAssignment(translatedNetworkResourceId)); } } @@ -61,35 +60,27 @@ public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTransla } @Override - protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement(TranslateTo translateTo) { return Optional.empty(); } - private NodeTemplate getTranslatedPolicyNodeTemplate(TranslateTo translateTo, - String heatFileName) { + private NodeTemplate getTranslatedPolicyNodeTemplate(TranslateTo translateTo, String heatFileName) { AttachedResourceId attachedPolicyResourceId = extractAttachedResourceIdHandleMissing(translateTo, "policy"); NodeTemplate policyNodeTemplate = new NodeTemplate(); - Optional<String> policyResourceId = - HeatToToscaUtil.getContrailAttachedHeatResourceId(attachedPolicyResourceId); + Optional<String> policyResourceId = HeatToToscaUtil.getContrailAttachedHeatResourceId(attachedPolicyResourceId); if (policyResourceId.isPresent()) { policyNodeTemplate = getPolicyNodeTemplate(translateTo, heatFileName, policyResourceId.get()); } else { - logger.warn(LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR, translateTo.getResourceId(), translateTo.getResource().getType()); } return policyNodeTemplate; } - private NodeTemplate getPolicyNodeTemplate(TranslateTo translateTo, String heatFileName, - String policyResourceId) { - Resource policyResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, heatFileName); - Optional<String> translatedPolicyResourceId = - ResourceTranslationFactory.getInstance(policyResource) - .translateResource(heatFileName, translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), policyResource, policyResourceId, - translateTo.getContext()); + private NodeTemplate getPolicyNodeTemplate(TranslateTo translateTo, String heatFileName, String policyResourceId) { + Resource policyResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, heatFileName); + Optional<String> translatedPolicyResourceId = ResourceTranslationFactory.getInstance(policyResource) + .translateResource(heatFileName, translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), policyResource, + policyResourceId, translateTo.getContext()); if (!translatedPolicyResourceId.isPresent()) { logger.warn(LOG_UNSUPPORTED_POLICY_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType()); return null; @@ -98,24 +89,18 @@ public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTransla } private String getTranslatedNetworkResourceId(TranslateTo translateTo) { - AttachedResourceId attachedNetworkResourceId = extractAttachedResourceIdHandleMissing(translateTo, - NETWORK_PROPERTY_NAME); - + AttachedResourceId attachedNetworkResourceId = extractAttachedResourceIdHandleMissing(translateTo, NETWORK_PROPERTY_NAME); String translatedNetworkResourceId = null; if (attachedNetworkResourceId.isGetResource()) { translatedNetworkResourceId = (String) attachedNetworkResourceId.getTranslatedId(); } else { - logger.warn(LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY, translateTo.getResourceId(), translateTo.getResource().getType()); } return translatedNetworkResourceId; } - private AttachedResourceId extractAttachedResourceIdHandleMissing( - TranslateTo translateTo, String propertyName) { - Optional<AttachedResourceId> attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); - + private AttachedResourceId extractAttachedResourceIdHandleMissing(TranslateTo translateTo, String propertyName) { + Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); if (!attachedResourceId.isPresent()) { throw new CoreException(new MissingMandatoryPropertyErrorBuilder(propertyName).build()); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java index b631573e24..6e58f6399e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -26,19 +25,16 @@ import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatT public class ResourceTranslationContrailNetworkPolicyImpl extends ResourceTranslationBase { - protected static Logger logger = - (Logger) LoggerFactory.getLogger(ResourceTranslationContrailNetworkPolicyImpl.class); + protected static Logger logger = (Logger) LoggerFactory.getLogger(ResourceTranslationContrailNetworkPolicyImpl.class); @Override protected void translate(TranslateTo translateTo) { NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAIL_NETWORK_RULE); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java index 305c034470..d4ee120fb8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.tosca.services.ToscaConstants.MANDATORY_PROPERTY_NAME; @@ -25,14 +24,25 @@ import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogCo import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION; +import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - -import org.onap.sdc.tosca.datatypes.model.*; +import org.onap.sdc.tosca.datatypes.model.AttributeDefinition; +import org.onap.sdc.tosca.datatypes.model.GroupDefinition; +import org.onap.sdc.tosca.datatypes.model.Import; +import org.onap.sdc.tosca.datatypes.model.NodeTemplate; +import org.onap.sdc.tosca.datatypes.model.NodeType; +import org.onap.sdc.tosca.datatypes.model.ParameterDefinition; +import org.onap.sdc.tosca.datatypes.model.PropertyDefinition; +import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; +import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; +import org.onap.sdc.tosca.datatypes.model.SubstitutionMapping; +import org.onap.sdc.tosca.datatypes.model.TopologyTemplate; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.heat.datatypes.HeatBoolean; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -63,8 +73,6 @@ import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypes import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import com.google.common.collect.ImmutableList; - public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTranslationBase { private static final String INTERFACE_LIST = "interface_list"; @@ -73,13 +81,11 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran @Override public void translate(TranslateTo translateTo) { Resource serviceInstanceResource = translateTo.getResource(); - AttachedResourceId contrailServiceTemplateAttached = getServiceTemplateAttachedId(translateTo, - serviceInstanceResource); + AttachedResourceId contrailServiceTemplateAttached = getServiceTemplateAttachedId(translateTo, serviceInstanceResource); if (contrailServiceTemplateAttached.isGetResource()) { translateContrailServiceInstance(translateTo, serviceInstanceResource, contrailServiceTemplateAttached); } else { - logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_GET_RESOURCE, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_GET_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType()); } } @@ -87,62 +93,49 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran AttachedResourceId contrailServiceTemplateAttached) { String contrailServiceTemplateResourceId = (String) contrailServiceTemplateAttached.getEntityId(); Resource contrailServiceTemplateResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), - contrailServiceTemplateResourceId, translateTo.getHeatFileName()); - if (!contrailServiceTemplateResource.getType() - .equals(HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource())) { - logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_INVALID_TYPE, translateTo.getResourceId(), - translateTo.getResource().getType(), contrailServiceTemplateResourceId, - contrailServiceTemplateResource.getType(), - HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource()); + .getResource(translateTo.getHeatOrchestrationTemplate(), contrailServiceTemplateResourceId, translateTo.getHeatFileName()); + if (!contrailServiceTemplateResource.getType().equals(HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource())) { + logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_INVALID_TYPE, translateTo.getResourceId(), translateTo.getResource().getType(), + contrailServiceTemplateResourceId, contrailServiceTemplateResource.getType(), + HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource()); return; } - Optional<String> contrailServiceTemplateTranslatedId = - ResourceTranslationFactory.getInstance(contrailServiceTemplateResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), contrailServiceTemplateResource, - contrailServiceTemplateResourceId, translateTo.getContext()); + Optional<String> contrailServiceTemplateTranslatedId = ResourceTranslationFactory.getInstance(contrailServiceTemplateResource) + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + contrailServiceTemplateResource, contrailServiceTemplateResourceId, translateTo.getContext()); if (!contrailServiceTemplateTranslatedId.isPresent()) { - logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE, translateTo.getResourceId(), - translateTo.getResource().getType(), contrailServiceTemplateResourceId, - contrailServiceTemplateResource.getType()); + logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType(), + contrailServiceTemplateResourceId, contrailServiceTemplateResource.getType()); return; } - ServiceTemplate globalSubstitutionServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); String contrailStId = ResourceTranslationContrailServiceTemplateImpl - .getContrailSubstitutedNodeTypeId(contrailServiceTemplateTranslatedId.get()); + .getContrailSubstitutedNodeTypeId(contrailServiceTemplateTranslatedId.get()); NodeType substitutedNodeType = DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, contrailStId); int numberOfPorts = getServiceInstanceNumberOfPorts(serviceInstanceResource); - if (substitutedNodeType.getRequirements() != null - && substitutedNodeType.getRequirements().size() != numberOfPorts) { + if (substitutedNodeType.getRequirements() != null && substitutedNodeType.getRequirements().size() != numberOfPorts) { logger.warn(LOG_MULTIPLE_SERVICE_INSTANCE_DIFF_INTERFACES, contrailServiceTemplateResourceId); return; } addNetworkLinkRequirements(substitutedNodeType, numberOfPorts); - NodeTemplate substitutedNodeTemplate = createSubstitutedNodeTemplate(translateTo, - contrailServiceTemplateResource, contrailStId, numberOfPorts); + NodeTemplate substitutedNodeTemplate = createSubstitutedNodeTemplate(translateTo, contrailServiceTemplateResource, contrailStId, + numberOfPorts); String computeNodeTypeId = new ContrailTranslationHelper() - .getComputeNodeTypeId(contrailServiceTemplateResource, contrailServiceTemplateResourceId, - contrailServiceTemplateTranslatedId.get(), translateTo.getContext()); + .getComputeNodeTypeId(contrailServiceTemplateResource, contrailServiceTemplateResourceId, contrailServiceTemplateTranslatedId.get(), + translateTo.getContext()); boolean orderedInterfaces = getOrderedInterfaces(contrailServiceTemplateResource); - ServiceTemplate nestedServiceTemplate = createNestedServiceTemplate(translateTo, computeNodeTypeId, - contrailStId, substitutedNodeTemplate, orderedInterfaces); - addAbstractSubstitutionProperty(translateTo, substitutedNodeTemplate.getProperties(), - nestedServiceTemplate, contrailServiceTemplateResource); + ServiceTemplate nestedServiceTemplate = createNestedServiceTemplate(translateTo, computeNodeTypeId, contrailStId, substitutedNodeTemplate, + orderedInterfaces); + addAbstractSubstitutionProperty(translateTo, substitutedNodeTemplate.getProperties(), nestedServiceTemplate, contrailServiceTemplateResource); translateTo.getContext().getTranslatedServiceTemplates().put(new ContrailTranslationHelper() - .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), - translateTo.getTranslatedId()), nestedServiceTemplate); + .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), translateTo.getTranslatedId()), nestedServiceTemplate); } - private void addAbstractSubstitutionProperty(TranslateTo translateTo, - Map<String, Object> substitutionProperties, - ServiceTemplate nestedServiceTemplate, - Resource contrailServiceTemplateResource) { + private void addAbstractSubstitutionProperty(TranslateTo translateTo, Map<String, Object> substitutionProperties, + ServiceTemplate nestedServiceTemplate, Resource contrailServiceTemplateResource) { Map<String, Object> innerProps = new HashMap<>(); - innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); Object countValue = handleScaleOutProperty(translateTo, innerProps); handleServiceScalingProperty(translateTo, innerProps, contrailServiceTemplateResource); boolean mandatory = false; @@ -157,16 +150,13 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } private Object handleScaleOutProperty(TranslateTo translateTo, Map<String, Object> innerProps) { - Object scaleOutPropertyValue = - translateTo.getResource().getProperties().get(HeatConstants.SCALE_OUT_PROPERTY_NAME); + Object scaleOutPropertyValue = translateTo.getResource().getProperties().get(HeatConstants.SCALE_OUT_PROPERTY_NAME); Object countValue = null; if (scaleOutPropertyValue instanceof Map) { countValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - Constants.MAX_INSTANCES_PROPERTY_NAME, - ((Map) scaleOutPropertyValue).get(Constants.MAX_INSTANCES_PROPERTY_NAME), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), null, - translateTo.getContext()); + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), Constants.MAX_INSTANCES_PROPERTY_NAME, + ((Map) scaleOutPropertyValue).get(Constants.MAX_INSTANCES_PROPERTY_NAME), null, translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), null, translateTo.getContext()); if (countValue != null) { innerProps.put(ToscaConstants.COUNT_PROPERTY_NAME, countValue); } else { @@ -178,21 +168,17 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran return countValue; } - private void handleServiceScalingProperty(TranslateTo translateTo, Map<String, Object> innerProps, - Resource contrailServiceTemplateResource) { - Object serviceScalingPropertyValue = contrailServiceTemplateResource.getProperties() - .get(HeatConstants.SERVICE_SCALING_PROPERTY_NAME); + private void handleServiceScalingProperty(TranslateTo translateTo, Map<String, Object> innerProps, Resource contrailServiceTemplateResource) { + Object serviceScalingPropertyValue = contrailServiceTemplateResource.getProperties().get(HeatConstants.SERVICE_SCALING_PROPERTY_NAME); Object serviceScalingValue; if (serviceScalingPropertyValue != null) { serviceScalingValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - HeatConstants.SERVICE_SCALING_PROPERTY_NAME, serviceScalingPropertyValue, null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), null, - translateTo.getContext()); + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), HeatConstants.SERVICE_SCALING_PROPERTY_NAME, + serviceScalingPropertyValue, null, translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), null, + translateTo.getContext()); if (serviceScalingValue != null) { innerProps.put(ToscaConstants.SCALING_ENABLED_PROPERTY_NAME, - (HeatBoolean.isValueBoolean(serviceScalingValue)) ? HeatBoolean.eval(serviceScalingValue) : - serviceScalingValue); + (HeatBoolean.isValueBoolean(serviceScalingValue)) ? HeatBoolean.eval(serviceScalingValue) : serviceScalingValue); } } } @@ -209,47 +195,37 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran return true; } - private ServiceTemplate createNestedServiceTemplate(TranslateTo translateTo, - String computeNodeTypeId, - String substitutedNodeTypeId, - NodeTemplate substitutedNodeTemplate, - boolean orderedInterfaces) { + private ServiceTemplate createNestedServiceTemplate(TranslateTo translateTo, String computeNodeTypeId, String substitutedNodeTypeId, + NodeTemplate substitutedNodeTemplate, boolean orderedInterfaces) { ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate(); setNestedServiceTemplateGeneralDetails(translateTo, nestedSubstitutionServiceTemplate); String heatStackGroupKey = addHeatStackGroup(translateTo, nestedSubstitutionServiceTemplate); addSubstitutionMappingEntry(nestedSubstitutionServiceTemplate, substitutedNodeTypeId); handleInputParameters(nestedSubstitutionServiceTemplate, translateTo); - String computeNodeTemplateId = handleComputeNodeTemplate(translateTo, computeNodeTypeId, - nestedSubstitutionServiceTemplate, heatStackGroupKey); + String computeNodeTemplateId = handleComputeNodeTemplate(translateTo, computeNodeTypeId, nestedSubstitutionServiceTemplate, + heatStackGroupKey); handleOutputParameters(nestedSubstitutionServiceTemplate, computeNodeTemplateId, translateTo); handleServiceInstanceInterfaces(translateTo, - new ContrailServiceInstanceTo(nestedSubstitutionServiceTemplate, substitutedNodeTemplate, - heatStackGroupKey, orderedInterfaces, computeNodeTemplateId)); + new ContrailServiceInstanceTo(nestedSubstitutionServiceTemplate, substitutedNodeTemplate, heatStackGroupKey, orderedInterfaces, + computeNodeTemplateId)); return nestedSubstitutionServiceTemplate; } - private void handleOutputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, - String nodeTemplateId, TranslateTo translateTo) { + private void handleOutputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, String nodeTemplateId, TranslateTo translateTo) { if (nodeTemplateId == null) { return; } ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - - Optional<NodeType> contrailAbstractNodeType = - toscaAnalyzerService.fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo - .getContext().getGlobalServiceTemplates().values()); - + Optional<NodeType> contrailAbstractNodeType = toscaAnalyzerService + .fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo.getContext().getGlobalServiceTemplates().values()); if (!contrailAbstractNodeType.isPresent()) { return; } - Map<String, AttributeDefinition> contrailAbstractAttributes = - contrailAbstractNodeType.get().getAttributes(); + Map<String, AttributeDefinition> contrailAbstractAttributes = contrailAbstractNodeType.get().getAttributes(); Map<String, ParameterDefinition> nestedSubstitutionServiceTemplateOutputs = new HashMap<>(); - if (contrailAbstractAttributes == null) { return; } - for (Map.Entry<String, AttributeDefinition> attributeDefinitionEntry : contrailAbstractAttributes.entrySet()) { AttributeDefinition abstractAttributeDef = attributeDefinitionEntry.getValue(); if (abstractAttributeDef != null) { @@ -258,22 +234,18 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran outputGetAttributeList.add(nodeTemplateId); outputGetAttributeList.add(attributeDefinitionEntry.getKey()); outputValue.put(ToscaFunctions.GET_ATTRIBUTE.getFunctionName(), outputGetAttributeList); - nestedSubstitutionServiceTemplateOutputs.put(attributeDefinitionEntry.getKey(), - DataModelUtil.convertAttributeDefToParameterDef(abstractAttributeDef, outputValue)); + nestedSubstitutionServiceTemplateOutputs + .put(attributeDefinitionEntry.getKey(), DataModelUtil.convertAttributeDefToParameterDef(abstractAttributeDef, outputValue)); } } - if (!nestedSubstitutionServiceTemplateOutputs.isEmpty()) { - nestedSubstitutionServiceTemplate.getTopology_template() - .setOutputs(nestedSubstitutionServiceTemplateOutputs); + nestedSubstitutionServiceTemplate.getTopology_template().setOutputs(nestedSubstitutionServiceTemplateOutputs); } } - private void handleServiceInstanceInterfaces(TranslateTo translateTo, - ContrailServiceInstanceTo contrailServiceInstanceTo) { + private void handleServiceInstanceInterfaces(TranslateTo translateTo, ContrailServiceInstanceTo contrailServiceInstanceTo) { Resource serviceInstanceResource = translateTo.getResource(); - Object interfaceListProperty = - serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); + Object interfaceListProperty = serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); if (interfaceListProperty == null) { return; } @@ -287,99 +259,76 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } } - private void handleInterface(TranslateTo translateTo, Object interfacePropertyValue, - Integer index, ContrailServiceInstanceTo contrailServiceInstanceTo) { + private void handleInterface(TranslateTo translateTo, Object interfacePropertyValue, Integer index, + ContrailServiceInstanceTo contrailServiceInstanceTo) { if (index == null) { index = 0; } NodeTemplate portNodeTemplate = createPortNodeTemplate(index, contrailServiceInstanceTo.isOrderedInterfaces(), - contrailServiceInstanceTo.getComputeNodeTemplateId()); + contrailServiceInstanceTo.getComputeNodeTemplateId()); String portNodeTemplateId = Constants.SERVICE_INSTANCE_PORT_PREFIX + index; String portReqMappingKey = Constants.SERVICE_INSTANCE_LINK_PREFIX + portNodeTemplateId; - - DataModelUtil.addNodeTemplate(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), - portNodeTemplateId, portNodeTemplate); - updateSubstitutionMappingRequirement(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), - portReqMappingKey, portNodeTemplateId); - updateHeatStackGroup(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), - contrailServiceInstanceTo.getHeatStackGroupKey(), portNodeTemplateId); - connectPortToNetwork(translateTo, interfacePropertyValue, contrailServiceInstanceTo - .getSubstitutedNodeTemplate(), portReqMappingKey); + DataModelUtil.addNodeTemplate(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), portNodeTemplateId, portNodeTemplate); + updateSubstitutionMappingRequirement(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), portReqMappingKey, portNodeTemplateId); + updateHeatStackGroup(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), contrailServiceInstanceTo.getHeatStackGroupKey(), + portNodeTemplateId); + connectPortToNetwork(translateTo, interfacePropertyValue, contrailServiceInstanceTo.getSubstitutedNodeTemplate(), portReqMappingKey); } - private void connectPortToNetwork(TranslateTo translateTo, Object interfacePropertyValue, - NodeTemplate substitutedNodeTemplate, + private void connectPortToNetwork(TranslateTo translateTo, Object interfacePropertyValue, NodeTemplate substitutedNodeTemplate, String portReqMappingKey) { - List<String> validNetworksForConnections = ImmutableList.of( - HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + List<String> validNetworksForConnections = ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); if (!(interfacePropertyValue instanceof Map)) { return; } Object virtualNetworkValue = ((Map) interfacePropertyValue).get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME); if (virtualNetworkValue == null) { - logger.warn(LOG_MISSING_VIRTUAL_NETWORK_INTERFACE_LIST, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_MISSING_VIRTUAL_NETWORK_INTERFACE_LIST, translateTo.getResourceId(), translateTo.getResource().getType()); return; } Optional<AttachedResourceId> networkAttachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getContext(), virtualNetworkValue); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + virtualNetworkValue); if (!networkAttachedResourceId.isPresent()) { return; } - Optional<String> networkResourceId = - HeatToToscaUtil.getContrailAttachedHeatResourceId(networkAttachedResourceId.get()); + Optional<String> networkResourceId = HeatToToscaUtil.getContrailAttachedHeatResourceId(networkAttachedResourceId.get()); if (networkResourceId.isPresent()) { - Resource networkResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - networkResourceId.get(), translateTo.getHeatFileName()); + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), translateTo.getHeatFileName()); if (validNetworksForConnections.contains(networkResource.getType())) { - Optional<String> networkTranslatedId = - getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), - translateTo.getContext()); - networkTranslatedId.ifPresent(translatedId -> addLinkToNetworkRequirementAssignment( - substitutedNodeTemplate, translatedId, portReqMappingKey)); - + Optional<String> networkTranslatedId = getResourceTranslatedId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), translateTo.getContext()); + networkTranslatedId + .ifPresent(translatedId -> addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, translatedId, portReqMappingKey)); } else { - logger.warn(LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION, translateTo.getResourceId(), translateTo.getResource().getType()); } - } else if (networkAttachedResourceId.get().isGetParam() - && networkAttachedResourceId.get().getEntityId() instanceof String) { + } else if (networkAttachedResourceId.get().isGetParam() && networkAttachedResourceId.get().getEntityId() instanceof String) { TranslatedHeatResource translatedSharedResourceId = translateTo.getContext().getHeatSharedResourcesByParam() - .get(networkAttachedResourceId.get().getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, - translatedSharedResourceId.getTranslatedId(), portReqMappingKey); + .get(networkAttachedResourceId.get().getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, translatedSharedResourceId.getTranslatedId(), portReqMappingKey); } } else { - logger.warn(LOG_INVALID_NETWORK_CONNECTION, translateTo.getResourceId(), - translateTo.getResource().getType(), virtualNetworkValue.toString()); + logger.warn(LOG_INVALID_NETWORK_CONNECTION, translateTo.getResourceId(), translateTo.getResource().getType(), + virtualNetworkValue.toString()); } } - private NodeTemplate createPortNodeTemplate(Integer index, boolean orderedInterfaces, - String computeNodeTemplateId) { + private NodeTemplate createPortNodeTemplate(Integer index, boolean orderedInterfaces, String computeNodeTemplateId) { NodeTemplate portNodeTemplate = new NodeTemplate(); portNodeTemplate.setType(ToscaNodeType.CONTRAIL_PORT); Map<String, Object> portProperties = new HashMap<>(); - portProperties.put("static_routes", DataModelUtil - .createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "static_routes")); - portProperties.put("virtual_network", DataModelUtil - .createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "virtual_network")); - portProperties.put("allowed_address_pairs", DataModelUtil - .createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, - "allowed_address_pairs")); - portProperties.put("ip_address", DataModelUtil - .createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "ip_address")); - portProperties.put("static_route", - DataModelUtil.createGetInputPropertyValueFromListParameter("static_routes_list", index)); - portProperties.put("shared_ip", - DataModelUtil.createGetInputPropertyValueFromListParameter("shared_ip_list", index)); - portProperties.put("interface_type", DataModelUtil - .createGetInputPropertyValueFromListParameter("service_interface_type_list", index)); + portProperties.put("static_routes", DataModelUtil.createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "static_routes")); + portProperties.put("virtual_network", DataModelUtil.createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "virtual_network")); + portProperties + .put("allowed_address_pairs", DataModelUtil.createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "allowed_address_pairs")); + portProperties.put("ip_address", DataModelUtil.createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "ip_address")); + portProperties.put("static_route", DataModelUtil.createGetInputPropertyValueFromListParameter("static_routes_list", index)); + portProperties.put("shared_ip", DataModelUtil.createGetInputPropertyValueFromListParameter("shared_ip_list", index)); + portProperties.put("interface_type", DataModelUtil.createGetInputPropertyValueFromListParameter("service_interface_type_list", index)); if (orderedInterfaces) { portProperties.put("order", index); } @@ -388,10 +337,7 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran return portNodeTemplate; } - - private void addLinkToNetworkRequirementAssignment(NodeTemplate nodeTemplate, - String connectedNodeTranslatedId, - String requirementId) { + private void addLinkToNetworkRequirementAssignment(NodeTemplate nodeTemplate, String connectedNodeTranslatedId, String requirementId) { if (nodeTemplate == null || connectedNodeTranslatedId == null) { return; } @@ -402,40 +348,35 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran DataModelUtil.addRequirementAssignment(nodeTemplate, requirementId, requirement); } - private void updateHeatStackGroup(ServiceTemplate serviceTemplate, String heatStackGroupKey, - String memberId) { + private void updateHeatStackGroup(ServiceTemplate serviceTemplate, String heatStackGroupKey, String memberId) { serviceTemplate.getTopology_template().getGroups().get(heatStackGroupKey).getMembers().add(memberId); } - private void updateSubstitutionMappingRequirement(ServiceTemplate serviceTemplate, - String portReqMappingKey, - String portNodeTemplateId) { + private void updateSubstitutionMappingRequirement(ServiceTemplate serviceTemplate, String portReqMappingKey, String portNodeTemplateId) { List<String> portReqMappingValue = new ArrayList<>(); portReqMappingValue.add(portNodeTemplateId); portReqMappingValue.add(ToscaConstants.LINK_REQUIREMENT_ID); DataModelUtil.addSubstitutionMappingReq(serviceTemplate, portReqMappingKey, portReqMappingValue); } - private void addSubstitutionMappingEntry(ServiceTemplate nestedSubstitutionServiceTemplate, - String substitutedNodeTypeId) { + private void addSubstitutionMappingEntry(ServiceTemplate nestedSubstitutionServiceTemplate, String substitutedNodeTypeId) { SubstitutionMapping substitutionMappings = new SubstitutionMapping(); substitutionMappings.setNode_type(substitutedNodeTypeId); DataModelUtil.addSubstitutionMapping(nestedSubstitutionServiceTemplate, substitutionMappings); } - private void handleInputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, - TranslateTo translateTo) { + private void handleInputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, TranslateTo translateTo) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - Optional<NodeType> contrailAbstractNodeType = toscaAnalyzerService.fetchNodeType(ToscaNodeType - .CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo.getContext().getGlobalServiceTemplates().values()); + Optional<NodeType> contrailAbstractNodeType = toscaAnalyzerService + .fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo.getContext().getGlobalServiceTemplates().values()); Map<String, ParameterDefinition> nestedSubstitutionServiceTemplateInputs = new HashMap<>(); if (contrailAbstractNodeType.isPresent()) { Map<String, PropertyDefinition> contrailAbstractProperties = contrailAbstractNodeType.get().getProperties(); for (Map.Entry<String, PropertyDefinition> propertyEntry : contrailAbstractProperties.entrySet()) { PropertyDefinition abstractPropertyDef = contrailAbstractProperties.get(propertyEntry.getKey()); if (abstractPropertyDef != null) { - nestedSubstitutionServiceTemplateInputs.put(propertyEntry.getKey(), - DataModelUtil.convertPropertyDefToParameterDef(abstractPropertyDef)); + nestedSubstitutionServiceTemplateInputs + .put(propertyEntry.getKey(), DataModelUtil.convertPropertyDefToParameterDef(abstractPropertyDef)); } } } @@ -444,12 +385,11 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } } - private String handleComputeNodeTemplate(TranslateTo translateTo, String computeNodeTypeId, - ServiceTemplate nestedSubstitutionServiceTemplate, + private String handleComputeNodeTemplate(TranslateTo translateTo, String computeNodeTypeId, ServiceTemplate nestedSubstitutionServiceTemplate, String heatStackGroupKey) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - Optional<NodeType> contrailComputeNodeType = toscaAnalyzerService.fetchNodeType(ToscaNodeType.CONTRAIL_COMPUTE, - translateTo.getContext().getGlobalServiceTemplates().values()); + Optional<NodeType> contrailComputeNodeType = toscaAnalyzerService + .fetchNodeType(ToscaNodeType.CONTRAIL_COMPUTE, translateTo.getContext().getGlobalServiceTemplates().values()); Map<String, Object> computeNodeTemplateProperties = null; if (contrailComputeNodeType.isPresent()) { Map<String, PropertyDefinition> contrailComputeProperties = contrailComputeNodeType.get().getProperties(); @@ -462,7 +402,6 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } } } - NodeTemplate computeNodeTemplate = new NodeTemplate(); computeNodeTemplate.setType(computeNodeTypeId); if (computeNodeTemplateProperties != null && !computeNodeTemplateProperties.isEmpty()) { @@ -470,8 +409,7 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } String computeNodeTemplateId = translateTo.getTranslatedId(); DataModelUtil.addNodeTemplate(nestedSubstitutionServiceTemplate, computeNodeTemplateId, computeNodeTemplate); - nestedSubstitutionServiceTemplate.getTopology_template().getGroups().get(heatStackGroupKey) - .getMembers().add(computeNodeTemplateId); + nestedSubstitutionServiceTemplate.getTopology_template().getGroups().get(heatStackGroupKey).getMembers().add(computeNodeTemplateId); return computeNodeTemplateId; } @@ -479,47 +417,34 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran GroupDefinition serviceInstanceGroupDefinition = new GroupDefinition(); serviceInstanceGroupDefinition.setType(ToscaGroupType.HEAT_STACK); Map<String, Object> groupProperties = new HashMap<>(); - groupProperties.put("heat_file", - "../" + (new ToscaFileOutputServiceCsarImpl()).getArtifactsFolderName() + "/" - + translateTo.getHeatFileName()); + groupProperties + .put("heat_file", "../" + (new ToscaFileOutputServiceCsarImpl()).getArtifactsFolderName() + "/" + translateTo.getHeatFileName()); serviceInstanceGroupDefinition.setProperties(groupProperties); serviceInstanceGroupDefinition.setMembers(new ArrayList<>()); String heatStackGroupKey = translateTo.getTranslatedId() + "_group"; - DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupKey, - serviceInstanceGroupDefinition); + DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupKey, serviceInstanceGroupDefinition); return heatStackGroupKey; } - - private void setNestedServiceTemplateGeneralDetails(TranslateTo translateTo, - ServiceTemplate - nestedSubstitutionServiceTemplate) { + private void setNestedServiceTemplateGeneralDetails(TranslateTo translateTo, ServiceTemplate nestedSubstitutionServiceTemplate) { Map<String, String> nestedTemplateMetadata = new HashMap<>(); String nestedTemplateName = new ContrailTranslationHelper() - .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), - translateTo.getResourceId()); + .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), translateTo.getResourceId()); nestedTemplateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, nestedTemplateName); nestedSubstitutionServiceTemplate.setMetadata(nestedTemplateMetadata); nestedSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate()); List<Map<String, Import>> globalTypesImportList = GlobalTypesGenerator.getGlobalTypesImportList(); - globalTypesImportList.addAll( - HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + globalTypesImportList.addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); nestedSubstitutionServiceTemplate.setImports(globalTypesImportList); } - private NodeTemplate createSubstitutedNodeTemplate(TranslateTo translateTo, - Resource contrailServiceTemplateResource, - String contrailServiceTemplateTranslatedId, - int numberOfPorts) { - boolean isImportAddedToServiceTemplate = - DataModelUtil - .isImportAddedToServiceTemplate(translateTo.getServiceTemplate().getImports(), Constants - .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + private NodeTemplate createSubstitutedNodeTemplate(TranslateTo translateTo, Resource contrailServiceTemplateResource, + String contrailServiceTemplateTranslatedId, int numberOfPorts) { + boolean isImportAddedToServiceTemplate = DataModelUtil + .isImportAddedToServiceTemplate(translateTo.getServiceTemplate().getImports(), Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); if (!isImportAddedToServiceTemplate) { - translateTo.getServiceTemplate().getImports() - .addAll(HeatToToscaUtil - .createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + translateTo.getServiceTemplate().getImports().addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); } NodeTemplate substitutesNodeTemplate = new NodeTemplate(); substitutesNodeTemplate.setType(contrailServiceTemplateTranslatedId); @@ -527,74 +452,53 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); substitutesNodeTemplate.setDirectives(directiveList); substitutesNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), - HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE.getHeatResource(), substitutesNodeTemplate, - translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE.getHeatResource(), substitutesNodeTemplate, + translateTo.getContext())); substitutesNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), contrailServiceTemplateResource.getProperties(), - substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), - HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource(), substitutesNodeTemplate, - translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + contrailServiceTemplateResource.getProperties(), substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource(), substitutesNodeTemplate, + translateTo.getContext())); HeatToToscaUtil.mapBoolean(substitutesNodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.AVAILABILITY_ZONE_ENABLE_PROPERTY_NAME)); + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.AVAILABILITY_ZONE_ENABLE_PROPERTY_NAME)); HeatToToscaUtil.mapBoolean(substitutesNodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.ORDERED_INTERFACES_PROPERTY_NAME)); - - Object sharedIpListPropertyValue = - contrailServiceTemplateResource.getProperties() - .get(HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.ORDERED_INTERFACES_PROPERTY_NAME)); + Object sharedIpListPropertyValue = contrailServiceTemplateResource.getProperties().get(HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); String toscaSharedIpListPropertyName = HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); - Optional<List<Map<String, List>>> sharedIpTranslatedSplitFun = - new ContrailTranslationHelper() - .translateFnSplitFunction(sharedIpListPropertyValue, numberOfPorts, true); + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); + Optional<List<Map<String, List>>> sharedIpTranslatedSplitFun = new ContrailTranslationHelper() + .translateFnSplitFunction(sharedIpListPropertyValue, numberOfPorts, true); if (sharedIpTranslatedSplitFun.isPresent()) { - substitutesNodeTemplate.getProperties() - .put(toscaSharedIpListPropertyName, sharedIpTranslatedSplitFun.get()); + substitutesNodeTemplate.getProperties().put(toscaSharedIpListPropertyName, sharedIpTranslatedSplitFun.get()); } else { HeatToToscaUtil.mapBooleanList(substitutesNodeTemplate, toscaSharedIpListPropertyName); } - - Object staticRouteListPropertyValue = - contrailServiceTemplateResource.getProperties() - .get(HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); + Object staticRouteListPropertyValue = contrailServiceTemplateResource.getProperties().get(HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); String toscaStaticRoutesListPropertyName = HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); - Optional<List<Map<String, List>>> staticRouteTranslatedSplitFun = - new ContrailTranslationHelper() - .translateFnSplitFunction(staticRouteListPropertyValue, numberOfPorts, true); + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); + Optional<List<Map<String, List>>> staticRouteTranslatedSplitFun = new ContrailTranslationHelper() + .translateFnSplitFunction(staticRouteListPropertyValue, numberOfPorts, true); if (staticRouteTranslatedSplitFun.isPresent()) { - substitutesNodeTemplate.getProperties() - .put(toscaStaticRoutesListPropertyName, staticRouteTranslatedSplitFun.get()); + substitutesNodeTemplate.getProperties().put(toscaStaticRoutesListPropertyName, staticRouteTranslatedSplitFun.get()); } else { HeatToToscaUtil.mapBooleanList(substitutesNodeTemplate, toscaStaticRoutesListPropertyName); } - - Object serviceInterfaceTypeListPropertyValue = - contrailServiceTemplateResource.getProperties() - .get(HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); + Object serviceInterfaceTypeListPropertyValue = contrailServiceTemplateResource.getProperties() + .get(HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); String toscaServiceInterfaceTypeListPropertyName = HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); - Optional<List<Map<String, List>>> serviceInterfaceTypeTranslatedSplitFun = - new ContrailTranslationHelper() - .translateFnSplitFunction(serviceInterfaceTypeListPropertyValue, numberOfPorts, false); - serviceInterfaceTypeTranslatedSplitFun - .ifPresent(translatedSplitFun -> substitutesNodeTemplate.getProperties() - .put(toscaServiceInterfaceTypeListPropertyName, translatedSplitFun)); - + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); + Optional<List<Map<String, List>>> serviceInterfaceTypeTranslatedSplitFun = new ContrailTranslationHelper() + .translateFnSplitFunction(serviceInterfaceTypeListPropertyValue, numberOfPorts, false); + serviceInterfaceTypeTranslatedSplitFun.ifPresent( + translatedSplitFun -> substitutesNodeTemplate.getProperties().put(toscaServiceInterfaceTypeListPropertyName, translatedSplitFun)); String substitutedNodeTemplateId = translateTo.getTranslatedId(); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutedNodeTemplateId, - substitutesNodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutedNodeTemplateId, substitutesNodeTemplate); return substitutesNodeTemplate; } @@ -603,10 +507,9 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>(); for (int i = 0; i < numberOfPorts; i++) { Map<String, RequirementDefinition> requirementDefinitionMap = new HashMap<>(); - requirementDefinitionMap.put(ToscaConstants.LINK_REQUIREMENT_ID + "_port_" + i, - DataModelUtil.createRequirement(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE, - ToscaNodeType.NATIVE_ROOT, - ToscaRelationshipType.NATIVE_NETWORK_LINK_TO, null)); + requirementDefinitionMap.put(ToscaConstants.LINK_REQUIREMENT_ID + "_port_" + i, DataModelUtil + .createRequirement(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE, ToscaNodeType.NATIVE_ROOT, + ToscaRelationshipType.NATIVE_NETWORK_LINK_TO, null)); requirementList.add(requirementDefinitionMap); } if (numberOfPorts > 0) { @@ -617,8 +520,7 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran private int getServiceInstanceNumberOfPorts(Resource serviceInstanceResource) { int numberOfPorts; - Object interfaceTypeProperty = - serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); + Object interfaceTypeProperty = serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); if (interfaceTypeProperty == null) { numberOfPorts = 0; } else if (interfaceTypeProperty instanceof List) { @@ -631,20 +533,15 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran return numberOfPorts; } - private AttachedResourceId getServiceTemplateAttachedId(TranslateTo translateTo, - Resource serviceInstanceResource) { - Object serviceTemplateProperty = - serviceInstanceResource.getProperties().get("service_template"); + private AttachedResourceId getServiceTemplateAttachedId(TranslateTo translateTo, Resource serviceInstanceResource) { + Object serviceTemplateProperty = serviceInstanceResource.getProperties().get("service_template"); Optional<AttachedResourceId> serviceTemplateId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - serviceTemplateProperty); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + serviceTemplateProperty); if (serviceTemplateId.isPresent()) { return serviceTemplateId.get(); } else { throw new CoreException(new MissingMandatoryPropertyErrorBuilder("service_template").build()); } } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java index a5eac91acb..456a499119 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.common.errors.CoreException; @@ -30,18 +33,12 @@ import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatory import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - public class ResourceTranslationContrailServiceTemplateImpl extends ResourceTranslationBase { private static final String IMAGE_NAME = "image_name"; static String getContrailSubstitutedNodeTypeId(String serviceTemplateTranslatedId) { - return ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + ToscaConstants.HEAT_NODE_TYPE_SUFFIX - + serviceTemplateTranslatedId; + return ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + ToscaConstants.HEAT_NODE_TYPE_SUFFIX + serviceTemplateTranslatedId; } @Override @@ -60,45 +57,39 @@ public class ResourceTranslationContrailServiceTemplateImpl extends ResourceTran return true; } - private void addComputeNodeType(TranslateTo translateTo, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { + private void addComputeNodeType(TranslateTo translateTo, ServiceTemplate globalSubstitutionServiceTemplate, TranslationContext context) { NodeType computeNodeType = new NodeType(); computeNodeType.setDerived_from(ToscaNodeType.CONTRAIL_COMPUTE); - String computeNodeTypeId = new ContrailTranslationHelper().getComputeNodeTypeId(translateTo.getResource(), - translateTo.getResourceId(), translateTo.getTranslatedId(), context); + String computeNodeTypeId = new ContrailTranslationHelper() + .getComputeNodeTypeId(translateTo.getResource(), translateTo.getResourceId(), translateTo.getTranslatedId(), context); DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, computeNodeTypeId, computeNodeType); } - private void addSubstitutedNodeType(TranslateTo translateTo, - ServiceTemplate globalSubstitutionServiceTemplate) { + private void addSubstitutedNodeType(TranslateTo translateTo, ServiceTemplate globalSubstitutionServiceTemplate) { NodeType substitutedNodeType = new NodeType(); substitutedNodeType.setDerived_from(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE); - DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, - getContrailSubstitutedNodeTypeId(translateTo.getTranslatedId()), substitutedNodeType); + DataModelUtil + .addNodeType(globalSubstitutionServiceTemplate, getContrailSubstitutedNodeTypeId(translateTo.getTranslatedId()), substitutedNodeType); } @Override - protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement(TranslateTo translateTo) { return Optional.empty(); } private ServiceTemplate getGlobalSubstitutionTypesServiceTemplate(TranslateTo translateTo) { ServiceTemplate globalSubstitutionServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); if (globalSubstitutionServiceTemplate == null) { globalSubstitutionServiceTemplate = new ServiceTemplate(); Map<String, String> templateMetadata = new HashMap<>(); - templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants - .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); globalSubstitutionServiceTemplate.setMetadata(templateMetadata); globalSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList()); globalSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - translateTo.getContext().getTranslatedServiceTemplates().put(Constants - .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate); + translateTo.getContext().getTranslatedServiceTemplates() + .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate); } return globalSubstitutionServiceTemplate; } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java index 32aaabc482..3cc4c0945d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -33,11 +32,9 @@ public class ResourceTranslationContrailV2NetworkPolicyImpl extends ResourceTran NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAILV2_NETWORK_RULE); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java index 556124baba..e7ccd2ba4e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java @@ -13,9 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.tosca.services.DataModelUtil.createAttachmentRequirementAssignment; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_PROPERTY_VALUE_FORMAT; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -33,11 +44,6 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.*; - -import static org.openecomp.sdc.tosca.services.DataModelUtil.createAttachmentRequirementAssignment; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.*; - public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTranslationBase { private static final String FQ_NAME = "fq_name"; @@ -48,13 +54,10 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VIRTUAL_NETWORK); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); linkToPolicyNodeTemplate(translateTo); } @@ -64,10 +67,10 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra return; } for (AttachedResourceId attachedResourceId : networkPolicyIdList) { - NodeTemplate policyNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), - (String) attachedResourceId.getTranslatedId()); + NodeTemplate policyNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), (String) attachedResourceId.getTranslatedId()); DataModelUtil.addRequirementAssignment(policyNodeTemplate, ToscaConstants.NETWORK_REQUIREMENT_ID, - createAttachmentRequirementAssignment(translateTo.getTranslatedId())); + createAttachmentRequirementAssignment(translateTo.getTranslatedId())); } } @@ -79,8 +82,7 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra return Collections.emptyList(); } - private List<AttachedResourceId> extractNetworkPolicyId(Object propertyValue, - TranslateTo translateTo) { + private List<AttachedResourceId> extractNetworkPolicyId(Object propertyValue, TranslateTo translateTo) { List<AttachedResourceId> attachedResourceIdList = new ArrayList<>(); if (propertyValue instanceof List) { for (Object value : (List) propertyValue) { @@ -101,20 +103,16 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra if (policyResourceId == null) { return null; } - - Resource policyResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - policyResourceId, translateTo.getHeatFileName()); - if (!policyResource.getType().equals(HeatResourcesTypes.CONTRAIL_V2_NETWORK_RULE_RESOURCE_TYPE - .getHeatResource())) { + Resource policyResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, translateTo.getHeatFileName()); + if (!policyResource.getType().equals(HeatResourcesTypes.CONTRAIL_V2_NETWORK_RULE_RESOURCE_TYPE.getHeatResource())) { return null; } translatedPolicyResourceId = ResourceTranslationFactory.getInstance(policyResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), policyResource, policyResourceId, - translateTo.getContext()); + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + policyResource, policyResourceId, translateTo.getContext()); if (!translatedPolicyResourceId.isPresent()) { - logger.warn(LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE, - translateTo.getResourceId(), translateTo.getResource().getType()); + logger.warn(LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType()); return null; } return new AttachedResourceId(translatedPolicyResourceId.get(), policyResourceId, ReferenceType.GET_ATTR); @@ -129,8 +127,7 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra return resourceId; } } - logger.warn(LOG_INVALID_PROPERTY_VALUE_FORMAT, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_INVALID_PROPERTY_VALUE_FORMAT, translateTo.getResourceId(), translateTo.getResource().getType()); return null; } @@ -155,8 +152,7 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra if (value.get(0) instanceof String) { return true; } else { - logger.warn(LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME, translateTo.getResourceId(), translateTo.getResource().getType()); } } return false; @@ -189,8 +185,7 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra if (value instanceof String) { return (String) value; } else { - logger.warn(LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType()); } return null; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java index 5e20d96ca8..3a80b9dfe4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java @@ -13,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_INTERFACE_VALUES; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; import org.openecomp.sdc.heat.datatypes.model.Resource; @@ -29,16 +35,8 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_INTERFACE_VALUES; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION; - - public class ResourceTranslationContrailV2VlanSubInterfaceImpl extends ResourceTranslationBase { + protected static Logger logger = LoggerFactory.getLogger(ResourceTranslationContrailV2VlanSubInterfaceImpl.class); @Override @@ -46,59 +44,45 @@ public class ResourceTranslationContrailV2VlanSubInterfaceImpl extends ResourceT NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); new ContrailV2VirtualMachineInterfaceHelper().connectVmiToNetwork(this, translateTo, nodeTemplate); connectSubInterfaceToInterface(translateTo, nodeTemplate); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } //connection to shared interface is not supported - private void connectSubInterfaceToInterface(TranslateTo translateTo, - NodeTemplate vlanSubInterfaceNodeTemplate) { + private void connectSubInterfaceToInterface(TranslateTo translateTo, NodeTemplate vlanSubInterfaceNodeTemplate) { Object interfaceRefs = translateTo.getResource().getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); - if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) - || ((List) interfaceRefs).isEmpty()) { + if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) || ((List) interfaceRefs).isEmpty()) { return; } - List<String> acceptableResourceTypes = Arrays - .asList(HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()); + List<String> acceptableResourceTypes = Arrays.asList(HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()); if (((List) interfaceRefs).size() > 1) { logger.warn(LOG_MULTIPLE_INTERFACE_VALUES, translateTo.getResourceId(), translateTo.getResource().getType(), - HeatConstants.VMI_REFS_PROPERTY_NAME); + HeatConstants.VMI_REFS_PROPERTY_NAME); } Object interfaceRef = ((List) interfaceRefs).get(0); - Optional<String> interfaceResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(interfaceRef); + Optional<String> interfaceResourceId = HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(interfaceRef); if (interfaceResourceId.isPresent()) { // get_resource - Resource interfaceResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - interfaceResourceId.get(), translateTo.getHeatFileName()); - - if (acceptableResourceTypes.contains(interfaceResource.getType()) - && !(new ContrailV2VirtualMachineInterfaceHelper() - .isVlanSubInterfaceResource(interfaceResource))) { - Optional<String> interfaceResourceTranslatedId = - getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), interfaceResourceId.get(), - translateTo.getContext()); + Resource interfaceResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), interfaceResourceId.get(), translateTo.getHeatFileName()); + if (acceptableResourceTypes.contains(interfaceResource.getType()) && !(new ContrailV2VirtualMachineInterfaceHelper() + .isVlanSubInterfaceResource(interfaceResource))) { + Optional<String> interfaceResourceTranslatedId = getResourceTranslatedId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), interfaceResourceId.get(), translateTo.getContext()); interfaceResourceTranslatedId.ifPresent(interfaceResourceTranslatedIdVal -> HeatToToscaUtil - .addBindingReqFromSubInterfaceToInterface(vlanSubInterfaceNodeTemplate, - interfaceResourceTranslatedIdVal)); + .addBindingReqFromSubInterfaceToInterface(vlanSubInterfaceNodeTemplate, interfaceResourceTranslatedIdVal)); } else { - logger.warn(LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION, translateTo.getResourceId(), translateTo - .getResource().getType(), HeatConstants.VMI_REFS_PROPERTY_NAME, - getLogMessage(interfaceResource), interfaceResourceId.get(), interfaceResource.getType()); + logger.warn(LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION, translateTo.getResourceId(), translateTo.getResource().getType(), + HeatConstants.VMI_REFS_PROPERTY_NAME, getLogMessage(interfaceResource), interfaceResourceId.get(), interfaceResource.getType()); } } } private String getLogMessage(Resource interfaceResource) { - return (new ContrailV2VirtualMachineInterfaceHelper().isVlanSubInterfaceResource(interfaceResource)) - ? "Vlan Sub interface " : ""; + return (new ContrailV2VirtualMachineInterfaceHelper().isVlanSubInterfaceResource(interfaceResource)) ? "Vlan Sub interface " : ""; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java index ebf107a385..6019e9f0b1 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.List; +import java.util.Map; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.heat.services.HeatConstants; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; @@ -25,74 +26,57 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.List; -import java.util.Map; - - public class ResourceTranslationContrailV2VmInterfaceImpl extends ResourceTranslationBase { - private final ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper = - new ContrailV2VirtualMachineInterfaceHelper(); + + private final ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper = new ContrailV2VirtualMachineInterfaceHelper(); @Override protected boolean isEssentialRequirementsValid(TranslateTo translateTo) { - if (contrailV2VirtualMachineInterfaceHelper - .isVlanSubInterfaceResource(translateTo.getResource())) { - return contrailV2VirtualMachineInterfaceHelper - .isVlanSubInterfaceConnectedToPortIndirectly(translateTo); + if (contrailV2VirtualMachineInterfaceHelper.isVlanSubInterfaceResource(translateTo.getResource())) { + return contrailV2VirtualMachineInterfaceHelper.isVlanSubInterfaceConnectedToPortIndirectly(translateTo); } return true; } @Override protected void translate(TranslateTo translateTo) { - if (contrailV2VirtualMachineInterfaceHelper - .isVlanSubInterfaceResource(translateTo.getResource())) { + if (contrailV2VirtualMachineInterfaceHelper.isVlanSubInterfaceResource(translateTo.getResource())) { translateVlanSubInterfaceResource(translateTo); } else { translateVirtualMachineInterfaceResource(translateTo); } } - private void translateVirtualMachineInterfaceResource(TranslateTo translateTo) { NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - String toscaVmiRefsPropertyName = - HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_REFS_PROPERTY_NAME); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + String toscaVmiRefsPropertyName = HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_REFS_PROPERTY_NAME); nodeTemplate.getProperties().remove(toscaVmiRefsPropertyName); handleVmiMacAddressesInProperties(translateTo, nodeTemplate); contrailV2VirtualMachineInterfaceHelper.connectVmiToNetwork(this, translateTo, nodeTemplate); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } - private void handleVmiMacAddressesInProperties(TranslateTo translateTo, - NodeTemplate nodeTemplate) { - String toscaVmiMacAddressesName = - HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES); + private void handleVmiMacAddressesInProperties(TranslateTo translateTo, NodeTemplate nodeTemplate) { + String toscaVmiMacAddressesName = HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES); String toscaVmiMacAddressesMacAddressesName = HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES_MAC_ADDRESSES); + .getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES_MAC_ADDRESSES); if (nodeTemplate.getProperties().containsKey(toscaVmiMacAddressesName)) { Object macAddressesValue = nodeTemplate.getProperties().get(toscaVmiMacAddressesName); - if (macAddressesValue instanceof Map && ((Map<String, Object>) macAddressesValue).containsKey( - toscaVmiMacAddressesMacAddressesName)) { - updateMacAddressesMacAddressesInProperties(nodeTemplate, toscaVmiMacAddressesName, - toscaVmiMacAddressesMacAddressesName, (Map<String, Object>) macAddressesValue); + if (macAddressesValue instanceof Map && ((Map<String, Object>) macAddressesValue).containsKey(toscaVmiMacAddressesMacAddressesName)) { + updateMacAddressesMacAddressesInProperties(nodeTemplate, toscaVmiMacAddressesName, toscaVmiMacAddressesMacAddressesName, + (Map<String, Object>) macAddressesValue); } } } - private void updateMacAddressesMacAddressesInProperties(NodeTemplate nodeTemplate, - String toscaVmiMacAddressesName, - String toscaVmiMacAddressesMacAddressesName, - Map<String, Object> macAddressesValue) { - Object macAddressesMacAddressesValue = - macAddressesValue.get(toscaVmiMacAddressesMacAddressesName); + private void updateMacAddressesMacAddressesInProperties(NodeTemplate nodeTemplate, String toscaVmiMacAddressesName, + String toscaVmiMacAddressesMacAddressesName, Map<String, Object> macAddressesValue) { + Object macAddressesMacAddressesValue = macAddressesValue.get(toscaVmiMacAddressesMacAddressesName); if (macAddressesMacAddressesValue instanceof List) { nodeTemplate.getProperties().put(toscaVmiMacAddressesName, macAddressesMacAddressesValue); } else { @@ -103,5 +87,4 @@ public class ResourceTranslationContrailV2VmInterfaceImpl extends ResourceTransl private void translateVlanSubInterfaceResource(TranslateTo translateTo) { new ResourceTranslationContrailV2VlanSubInterfaceImpl().translate(translateTo); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java index 0dea8b7172..6523f8092d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -29,11 +28,9 @@ public class ResourceTranslationContrailVirtualNetworkImpl extends ResourceTrans NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAIL_VIRTUAL_NETWORK); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java index f5571c9804..05b5a6b87e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java @@ -13,21 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.Optional; import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import java.util.Optional; - public class ResourceTranslationDefaultImpl extends ResourceTranslationBase { @Override public void translate(TranslateTo translateTo) { //no translation is needed, this default is used for unsupported resources - logger.warn("Heat resource: '{}' with type: '{}' is not supported, will be ignored in TOSCA translation", - translateTo.getResourceId(), translateTo.getResource().getType()); + logger.warn("Heat resource: '{}' with type: '{}' is not supported, will be ignored in TOSCA translation", translateTo.getResourceId(), + translateTo.getResource().getType()); } @Override @@ -36,9 +34,7 @@ public class ResourceTranslationDefaultImpl extends ResourceTranslationBase { } @Override - protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement(TranslateTo translateTo) { return Optional.empty(); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java index c6c444c135..063cbf40a6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -42,10 +44,6 @@ import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.TranslationService; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - public class ResourceTranslationNestedImpl extends ResourceTranslationBase { private static final String SUB_INTERFACE_COUNT = "count"; @@ -56,8 +54,8 @@ public class ResourceTranslationNestedImpl extends ResourceTranslationBase { TranslationContext context = translateTo.getContext(); FileData nestedFileData = HeatToToscaUtil.getFileData(translateTo.getResource().getType(), context); if (nestedFileData == null) { - log.warn("Nested File '{}' is not exist, therefore, the nested resource with the ID '{}' will be ignored " - + "in TOSCA translation", translateTo.getResource().getType(), translateTo.getResourceId()); + log.warn("Nested File '{}' is not exist, therefore, the nested resource with the ID '{}' will be ignored " + "in TOSCA translation", + translateTo.getResource().getType(), translateTo.getResourceId()); return; } String templateName = FileUtils.getFileWithoutExtention(translateTo.getResource().getType()); @@ -65,18 +63,15 @@ public class ResourceTranslationNestedImpl extends ResourceTranslationBase { if (!context.getTranslatedServiceTemplates().containsKey(translateTo.getResource().getType())) { translateNestedHeat(translateTo, nestedFileData, templateName, substitutionNodeTypeKey); } - ServiceTemplate substitutionServiceTemplate = context.getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()); + ServiceTemplate substitutionServiceTemplate = context.getTranslatedServiceTemplates().get(translateTo.getResource().getType()); if (DataModelUtil.isNodeTemplateSectionMissingFromServiceTemplate(substitutionServiceTemplate)) { handleSubstitutionServiceTemplateWithoutNodeTemplates(templateName, translateTo); return; } - NodeTemplate substitutionNodeTemplate = HeatToToscaUtil.createAbstractSubstitutionNodeTemplate(translateTo, - templateName, substitutionNodeTypeKey); - manageSubstitutionNodeTemplateConnectionPoint(translateTo, nestedFileData, substitutionNodeTemplate, - substitutionNodeTypeKey); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - substitutionNodeTemplate); + NodeTemplate substitutionNodeTemplate = HeatToToscaUtil + .createAbstractSubstitutionNodeTemplate(translateTo, templateName, substitutionNodeTypeKey); + manageSubstitutionNodeTemplateConnectionPoint(translateTo, nestedFileData, substitutionNodeTemplate, substitutionNodeTypeKey); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), substitutionNodeTemplate); //Add nested node template id to consolidation data ConsolidationDataUtil.updateNestedNodeTemplateId(translateTo); //Gather consolidation data if the resource group represents a sub interface @@ -86,69 +81,48 @@ public class ResourceTranslationNestedImpl extends ResourceTranslationBase { } private boolean isResourceGroupSubInterface(String substitutionNodeTypeKey) { - return StringUtils.isNotBlank(substitutionNodeTypeKey) - && substitutionNodeTypeKey.contains(ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX); + return StringUtils.isNotBlank(substitutionNodeTypeKey) && substitutionNodeTypeKey + .contains(ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX); } - private void translateNestedHeat(TranslateTo translateTo, FileData nestedFileData, String templateName, - String substitutionNodeTypeKey) { + private void translateNestedHeat(TranslateTo translateTo, FileData nestedFileData, String templateName, String substitutionNodeTypeKey) { TranslationContext context = translateTo.getContext(); //substitution service template - ServiceTemplate nestedSubstitutionServiceTemplate = - createSubstitutionServiceTemplate(translateTo, nestedFileData, templateName); + ServiceTemplate nestedSubstitutionServiceTemplate = createSubstitutionServiceTemplate(translateTo, nestedFileData, templateName); //global substitution service template ServiceTemplate globalSubstitutionServiceTemplate = HeatToToscaUtil - .fetchGlobalSubstitutionServiceTemplate(translateTo.getServiceTemplate(), context); + .fetchGlobalSubstitutionServiceTemplate(translateTo.getServiceTemplate(), context); //substitution node type NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() - .createInitSubstitutionNodeType(nestedSubstitutionServiceTemplate, ToscaNodeType.ABSTRACT_SUBSTITUTE); - DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeKey, - substitutionNodeType); + .createInitSubstitutionNodeType(nestedSubstitutionServiceTemplate, ToscaNodeType.ABSTRACT_SUBSTITUTE); + DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeKey, substitutionNodeType); //substitution mapping - HeatToToscaUtil.handleSubstitutionMapping(context, substitutionNodeTypeKey, - nestedSubstitutionServiceTemplate, substitutionNodeType); + HeatToToscaUtil.handleSubstitutionMapping(context, substitutionNodeTypeKey, nestedSubstitutionServiceTemplate, substitutionNodeType); //add new nested service template - context.getTranslatedServiceTemplates().put(translateTo.getResource().getType(), - nestedSubstitutionServiceTemplate); + context.getTranslatedServiceTemplates().put(translateTo.getResource().getType(), nestedSubstitutionServiceTemplate); } - private void populateSubInterfaceTemplateConsolidationData(TranslateTo translateTo, - NodeTemplate nodeTemplate) { - - SubInterfaceConsolidationDataHandler consolidationDataHandler = - translateTo.getContext().getSubInterfaceConsolidationDataHandler(); - + private void populateSubInterfaceTemplateConsolidationData(TranslateTo translateTo, NodeTemplate nodeTemplate) { + SubInterfaceConsolidationDataHandler consolidationDataHandler = translateTo.getContext().getSubInterfaceConsolidationDataHandler(); String translatedId = translateTo.getTranslatedId(); - Optional<String> subInterfaceNetworkRole = - HeatToToscaUtil.getNetworkRoleFromSubInterfaceId(translateTo.getResource(), translateTo.getContext()); - subInterfaceNetworkRole.ifPresent(networkRole -> consolidationDataHandler.setNetworkRole(translateTo, - translatedId, networkRole)); - - consolidationDataHandler.setResourceGroupCount(translateTo, translatedId, - getSubInterfaceCountFromResourceProperties(translateTo)); - + Optional<String> subInterfaceNetworkRole = HeatToToscaUtil + .getNetworkRoleFromSubInterfaceId(translateTo.getResource(), translateTo.getContext()); + subInterfaceNetworkRole.ifPresent(networkRole -> consolidationDataHandler.setNetworkRole(translateTo, translatedId, networkRole)); + consolidationDataHandler.setResourceGroupCount(translateTo, translatedId, getSubInterfaceCountFromResourceProperties(translateTo)); if (CollectionUtils.isEmpty(nodeTemplate.getRequirements())) { return; } //Add connectivity to network in consolidation data based on resource group link requirements - nodeTemplate.getRequirements().forEach((Map<String, RequirementAssignment> requirementMap) -> - requirementMap.entrySet().stream() - .filter(requirementAssignmentEntry -> ToscaCapabilityType.NATIVE_NETWORK_LINKABLE - .equals(requirementAssignmentEntry.getValue().getCapability())) - .forEach(requirementAssignmentEntry -> - consolidationDataHandler.addNodesConnectedOut(translateTo, - requirementAssignmentEntry.getValue().getNode(), - requirementAssignmentEntry.getKey(), - requirementAssignmentEntry.getValue()) - ) - ); + nodeTemplate.getRequirements().forEach((Map<String, RequirementAssignment> requirementMap) -> requirementMap.entrySet().stream().filter( + requirementAssignmentEntry -> ToscaCapabilityType.NATIVE_NETWORK_LINKABLE.equals(requirementAssignmentEntry.getValue().getCapability())) + .forEach(requirementAssignmentEntry -> consolidationDataHandler + .addNodesConnectedOut(translateTo, requirementAssignmentEntry.getValue().getNode(), requirementAssignmentEntry.getKey(), + requirementAssignmentEntry.getValue()))); } private Object getSubInterfaceCountFromResourceProperties(TranslateTo translateTo) { - if (Objects.nonNull(translateTo.getHeatOrchestrationTemplate().getResources().get(translateTo - .getResourceId()))) { - Resource resource = translateTo.getHeatOrchestrationTemplate().getResources().get(translateTo - .getResourceId()); + if (Objects.nonNull(translateTo.getHeatOrchestrationTemplate().getResources().get(translateTo.getResourceId()))) { + Resource resource = translateTo.getHeatOrchestrationTemplate().getResources().get(translateTo.getResourceId()); if (HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource().equals(resource.getType())) { return resource.getProperties().get(SUB_INTERFACE_COUNT); } else if (HeatToToscaUtil.isYamlFile(resource.getType())) { @@ -158,102 +132,69 @@ public class ResourceTranslationNestedImpl extends ResourceTranslationBase { return null; } - private void handleSubstitutionServiceTemplateWithoutNodeTemplates(String templateName, - TranslateTo translateTo) { + private void handleSubstitutionServiceTemplateWithoutNodeTemplates(String templateName, TranslateTo translateTo) { translateTo.getContext().addServiceTemplateWithoutNodeTemplates(templateName); - translateTo.getContext() - .addNestedNodeTemplateIdPointsToStWithoutNodeTemplates(translateTo.getTranslatedId()); + translateTo.getContext().addNestedNodeTemplateIdPointsToStWithoutNodeTemplates(translateTo.getTranslatedId()); translateTo.getContext().getTranslatedServiceTemplates().remove(translateTo.getResource().getType()); } - private ServiceTemplate createSubstitutionServiceTemplate(TranslateTo translateTo, - FileData nestedFileData, - String templateName) { - ServiceTemplate nestedSubstitutionServiceTemplate = - HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); - translateTo.getContext().addNestedHeatFileName(ToscaUtil.getServiceTemplateFileName(templateName), - translateTo.getResource().getType()); - new TranslationService().translateHeatFile(nestedSubstitutionServiceTemplate, nestedFileData, translateTo - .getContext()); + private ServiceTemplate createSubstitutionServiceTemplate(TranslateTo translateTo, FileData nestedFileData, String templateName) { + ServiceTemplate nestedSubstitutionServiceTemplate = HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); + translateTo.getContext().addNestedHeatFileName(ToscaUtil.getServiceTemplateFileName(templateName), translateTo.getResource().getType()); + new TranslationService().translateHeatFile(nestedSubstitutionServiceTemplate, nestedFileData, translateTo.getContext()); return nestedSubstitutionServiceTemplate; } - - private void manageSubstitutionNodeTemplateConnectionPoint(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - String substitutionNodeTypeId) { - ServiceTemplate globalSubstitutionTemplate = - translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + private void manageSubstitutionNodeTemplateConnectionPoint(TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, String substitutionNodeTypeId) { + ServiceTemplate globalSubstitutionTemplate = translateTo.getContext().getTranslatedServiceTemplates() + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); NodeType nodeType = globalSubstitutionTemplate.getNode_types().get(substitutionNodeTypeId); handlePortToNetConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - handleSecurityRulesToPortConnections(translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); + handleSecurityRulesToPortConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); handleNovaToVolConnection(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - handleContrailV2VmInterfaceToNetworkConnection(translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); - handleContrailPortToNetConnections(translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); - handleVlanSubInterfaceToInterfaceConnections(translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + handleContrailV2VmInterfaceToNetworkConnection(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + handleContrailPortToNetConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + handleVlanSubInterfaceToInterfaceConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } - private void handleVlanSubInterfaceToInterfaceConnections(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, + private void handleVlanSubInterfaceToInterfaceConnections(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - ContrailV2VlanToInterfaceResourceConnection linker = - new ContrailV2VlanToInterfaceResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + ContrailV2VlanToInterfaceResourceConnection linker = new ContrailV2VlanToInterfaceResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); linker.connect(); } - - private void handleContrailV2VmInterfaceToNetworkConnection(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { - ContrailV2VmInterfaceToNetResourceConnection linker = - new ContrailV2VmInterfaceToNetResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + private void handleContrailV2VmInterfaceToNetworkConnection(TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { + ContrailV2VmInterfaceToNetResourceConnection linker = new ContrailV2VmInterfaceToNetResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); linker.connect(); } - private void handleNovaToVolConnection(TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - NovaToVolResourceConnection linker = - new NovaToVolResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); + private void handleNovaToVolConnection(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + NovaToVolResourceConnection linker = new NovaToVolResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); linker.connect(); } - private void handleSecurityRulesToPortConnections(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, + private void handleSecurityRulesToPortConnections(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - SecurityRulesToPortResourceConnection linker = - new SecurityRulesToPortResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + SecurityRulesToPortResourceConnection linker = new SecurityRulesToPortResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); linker.connect(); } - private void handlePortToNetConnections(TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, + private void handlePortToNetConnections(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - PortToNetResourceConnection linker = - new PortToNetResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); + PortToNetResourceConnection linker = new PortToNetResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); linker.connect(); } - private void handleContrailPortToNetConnections(TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, + private void handleContrailPortToNetConnections(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - ContrailPortToNetResourceConnection linker = - new ContrailPortToNetResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + ContrailPortToNetResourceConnection linker = new ContrailPortToNetResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); linker.connect(); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java index 3fc05f43a1..798ed46d33 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -24,7 +23,6 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - public class ResourceTranslationNeutronNetImpl extends ResourceTranslationBase { @Override @@ -32,22 +30,13 @@ public class ResourceTranslationNeutronNetImpl extends ResourceTranslationBase { NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.NEUTRON_NET); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - - HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.PORT_SECURITY_ENABLED_PROPERTY_NAME)); - HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.SHARED_PROPERTY_NAME)); - HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.ADMIN_STATE_UP_PROPERTY_NAME)); - - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + HeatToToscaUtil + .mapBoolean(nodeTemplate, HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.PORT_SECURITY_ENABLED_PROPERTY_NAME)); + HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.SHARED_PROPERTY_NAME)); + HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.ADMIN_STATE_UP_PROPERTY_NAME)); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java index ee5097eb7a..939a5306ac 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java @@ -13,10 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.SECURITY_GROUPS_PROPERTY_NAME; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION; + import com.google.common.collect.ImmutableList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -37,12 +44,6 @@ import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFact import org.openecomp.sdc.translator.services.heattotosca.helper.ResourceTranslationNeutronPortHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.*; - -import static org.openecomp.sdc.translator.services.heattotosca.Constants.SECURITY_GROUPS_PROPERTY_NAME; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION; - - public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase { @Override @@ -50,17 +51,13 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.NEUTRON_PORT); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - new ResourceTranslationNeutronPortHelper().setAdditionalProperties(nodeTemplate - .getProperties()); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + new ResourceTranslationNeutronPortHelper().setAdditionalProperties(nodeTemplate.getProperties()); handleNetworkRequirement(translateTo, nodeTemplate); String resourceTranslatedId = handleSecurityRulesRequirement(translateTo); - DataModelUtil - .addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId, nodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId, nodeTemplate); } private String handleSecurityRulesRequirement(TranslateTo translateTo) { @@ -71,19 +68,18 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase List securityGroupsList = (List) securityGroups.get(); securityGroupsList.forEach(resourceValue -> { Optional<AttachedResourceId> securityGroupResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), resourceValue); - securityGroupResourceId.ifPresent(attachedResourceId -> handleSecurityGroupResourceId(translateTo, - resourceTranslatedId, attachedResourceId)); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + resourceValue); + securityGroupResourceId + .ifPresent(attachedResourceId -> handleSecurityGroupResourceId(translateTo, resourceTranslatedId, attachedResourceId)); }); } return resourceTranslatedId; } - private void handleSecurityGroupResourceId(TranslateTo translateTo, String resourceTranslatedId, - AttachedResourceId securityGroupResourceId) { + private void handleSecurityGroupResourceId(TranslateTo translateTo, String resourceTranslatedId, AttachedResourceId securityGroupResourceId) { List<String> supportedSecurityGroupsTypes = Collections - .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); + .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); if (securityGroupResourceId.isGetResource()) { handleGetResource(translateTo, resourceTranslatedId, securityGroupResourceId, supportedSecurityGroupsTypes); } else if (securityGroupResourceId.isGetParam()) { @@ -91,77 +87,64 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase } } - private void handleGetParam(TranslateTo translateTo, String resourceTranslatedId, - AttachedResourceId securityGroupResourceId, + private void handleGetParam(TranslateTo translateTo, String resourceTranslatedId, AttachedResourceId securityGroupResourceId, List<String> supportedSecurityGroupsTypes) { if (!(securityGroupResourceId.getEntityId() instanceof String)) { return; } - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam().get(securityGroupResourceId.getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, - translatedSharedResourceId.getHeatResource(), SECURITY_GROUPS_PROPERTY_NAME)) { + TranslatedHeatResource translatedSharedResourceId = translateTo.getContext().getHeatSharedResourcesByParam() + .get(securityGroupResourceId.getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, translatedSharedResourceId.getHeatResource(), + SECURITY_GROUPS_PROPERTY_NAME)) { return; } final NodeTemplate securityGroupNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), - translatedSharedResourceId.getTranslatedId()); + .getNodeTemplate(translateTo.getServiceTemplate(), translatedSharedResourceId.getTranslatedId()); RequirementAssignment requirement = new RequirementAssignment(); requirement.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); requirement.setNode(resourceTranslatedId); requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO); - DataModelUtil.addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, - requirement); - - ConsolidationDataUtil.updateNodesConnectedIn(translateTo, translatedSharedResourceId.getTranslatedId(), - ConsolidationEntityType.PORT, translateTo.getResourceId(), - ToscaConstants.PORT_REQUIREMENT_ID, requirement); + DataModelUtil.addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, requirement); + ConsolidationDataUtil.updateNodesConnectedIn(translateTo, translatedSharedResourceId.getTranslatedId(), ConsolidationEntityType.PORT, + translateTo.getResourceId(), ToscaConstants.PORT_REQUIREMENT_ID, requirement); } } - private void handleGetResource(TranslateTo translateTo, String resourceTranslatedId, - AttachedResourceId securityGroupResourceId, + private void handleGetResource(TranslateTo translateTo, String resourceTranslatedId, AttachedResourceId securityGroupResourceId, List<String> supportedSecurityGroupsTypes) { String resourceId = (String) securityGroupResourceId.getEntityId(); - Resource securityGroupResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - resourceId, translateTo.getHeatFileName()); + Resource securityGroupResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), resourceId, translateTo.getHeatFileName()); Optional<String> securityGroupTranslatedId = ResourceTranslationFactory.getInstance(securityGroupResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), securityGroupResource, resourceId, - translateTo.getContext()); + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + securityGroupResource, resourceId, translateTo.getContext()); if (!securityGroupTranslatedId.isPresent()) { return; } - if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, - securityGroupResource, SECURITY_GROUPS_PROPERTY_NAME)) { + if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, securityGroupResource, + SECURITY_GROUPS_PROPERTY_NAME)) { return; } final NodeTemplate securityGroupNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), securityGroupTranslatedId.get()); + .getNodeTemplate(translateTo.getServiceTemplate(), securityGroupTranslatedId.get()); RequirementAssignment requirement = new RequirementAssignment(); requirement.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); requirement.setNode(resourceTranslatedId); requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO); - DataModelUtil - .addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, - requirement); - - ConsolidationDataUtil.updateNodesConnectedIn(translateTo, securityGroupTranslatedId.get(), - ConsolidationEntityType.PORT, translateTo.getResourceId(), + DataModelUtil.addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, requirement); + ConsolidationDataUtil + .updateNodesConnectedIn(translateTo, securityGroupTranslatedId.get(), ConsolidationEntityType.PORT, translateTo.getResourceId(), ToscaConstants.PORT_REQUIREMENT_ID, requirement); } private void handleNetworkRequirement(TranslateTo translateTo, NodeTemplate nodeTemplate) { - Optional<AttachedResourceId> networkResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_PROPERTY_NAME); + Optional<AttachedResourceId> networkResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_PROPERTY_NAME); if (networkResourceId.isPresent()) { AttachedResourceId attachedResourceId = networkResourceId.get(); addRequirementAssignmentForNetworkResource(translateTo, nodeTemplate, attachedResourceId); } else { - networkResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants - .NETWORK_ID_PROPERTY_NAME); + networkResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_ID_PROPERTY_NAME); if (networkResourceId.isPresent()) { AttachedResourceId attachedResourceId = networkResourceId.get(); addRequirementAssignmentForNetworkResource(translateTo, nodeTemplate, attachedResourceId); @@ -169,8 +152,7 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase } } - private void addRequirementAssignmentForNetworkResource(TranslateTo translateTo, - NodeTemplate nodeTemplate, + private void addRequirementAssignmentForNetworkResource(TranslateTo translateTo, NodeTemplate nodeTemplate, AttachedResourceId attachedResourceId) { if (attachedResourceId.isGetResource()) { addLinkRequirementForGetResource(translateTo, nodeTemplate, attachedResourceId); @@ -179,60 +161,49 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase } } - private void addLinkRequirementForGetParam(TranslateTo translateTo, NodeTemplate nodeTemplate, - AttachedResourceId attachedResourceId) { - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam().get(attachedResourceId.getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + private void addLinkRequirementForGetParam(TranslateTo translateTo, NodeTemplate nodeTemplate, AttachedResourceId attachedResourceId) { + TranslatedHeatResource translatedSharedResourceId = translateTo.getContext().getHeatSharedResourcesByParam() + .get(attachedResourceId.getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { if (validateResourceTypeSupportedForReqCreation(translateTo, getSupportedNetworkResourceTypes(), - translatedSharedResourceId.getHeatResource(), "network'\\'network_id")) { + translatedSharedResourceId.getHeatResource(), "network'\\'network_id")) { return; } - RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( - nodeTemplate, translatedSharedResourceId.getTranslatedId()); - - ConsolidationDataUtil.updateNodesConnectedOut(translateTo, - translatedSharedResourceId.getTranslatedId(), ConsolidationEntityType.PORT, - ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + RequirementAssignment requirementAssignment = HeatToToscaUtil + .addLinkReqFromPortToNetwork(nodeTemplate, translatedSharedResourceId.getTranslatedId()); + ConsolidationDataUtil.updateNodesConnectedOut(translateTo, translatedSharedResourceId.getTranslatedId(), ConsolidationEntityType.PORT, + ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); } } - private void addLinkRequirementForGetResource(TranslateTo translateTo, NodeTemplate nodeTemplate, - AttachedResourceId attachedResourceId) { + private void addLinkRequirementForGetResource(TranslateTo translateTo, NodeTemplate nodeTemplate, AttachedResourceId attachedResourceId) { String networkTranslatedId; - Resource networkHeatResource = translateTo.getHeatOrchestrationTemplate() - .getResources().get(attachedResourceId.getEntityId()); - if (validateResourceTypeSupportedForReqCreation(translateTo, getSupportedNetworkResourceTypes(), - networkHeatResource, "network'\\'network_id")) { + Resource networkHeatResource = translateTo.getHeatOrchestrationTemplate().getResources().get(attachedResourceId.getEntityId()); + if (validateResourceTypeSupportedForReqCreation(translateTo, getSupportedNetworkResourceTypes(), networkHeatResource, + "network'\\'network_id")) { return; } networkTranslatedId = (String) attachedResourceId.getTranslatedId(); - RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( - nodeTemplate, networkTranslatedId); - - ConsolidationDataUtil.updateNodesConnectedOut(translateTo, networkTranslatedId, - ConsolidationEntityType.PORT, ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork(nodeTemplate, networkTranslatedId); + ConsolidationDataUtil + .updateNodesConnectedOut(translateTo, networkTranslatedId, ConsolidationEntityType.PORT, ToscaConstants.LINK_REQUIREMENT_ID, + requirementAssignment); } - - private boolean validateResourceTypeSupportedForReqCreation(TranslateTo translateTo, - List<String> supportedTypes, - Resource heatResource, + private boolean validateResourceTypeSupportedForReqCreation(TranslateTo translateTo, List<String> supportedTypes, Resource heatResource, final String propertyName) { if (isUnsupportedResourceType(heatResource, supportedTypes)) { String supportedResourceTypes = supportedTypes.toString(); - logger.warn(LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION, propertyName, translateTo - .getResourceId(), heatResource.getType(), supportedResourceTypes); + logger.warn(LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION, propertyName, translateTo.getResourceId(), heatResource.getType(), + supportedResourceTypes); return true; } return false; } - private List<String> getSupportedNetworkResourceTypes() { return ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java index 060544fd1b..35f274e023 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -22,7 +21,6 @@ import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - public class ResourceTranslationNeutronSecurityGroupImpl extends ResourceTranslationBase { @Override @@ -30,15 +28,9 @@ public class ResourceTranslationNeutronSecurityGroupImpl extends ResourceTransla NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.NEUTRON_SECURITY_RULES); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java index 7dedc6b9cf..37d39aa046 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.ParameterDefinition; import org.onap.sdc.tosca.datatypes.model.PropertyType; @@ -35,10 +37,6 @@ import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFact import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBase { private static final Logger logger = LoggerFactory.getLogger(ResourceTranslationNeutronSubnetImpl.class); @@ -50,47 +48,39 @@ public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBas if (!subnetNetwork.get().isGetResource()) { return; } - Resource networkResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - (String) subnetNetwork.get().getEntityId(), translateTo.getHeatFileName()); + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), (String) subnetNetwork.get().getEntityId(), translateTo.getHeatFileName()); Optional<String> translatedNetworkId = ResourceTranslationFactory.getInstance(networkResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), networkResource, - (String) subnetNetwork.get().getEntityId(), translateTo.getContext()); + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + networkResource, (String) subnetNetwork.get().getEntityId(), translateTo.getContext()); if (!translatedNetworkId.isPresent()) { return; } - NodeTemplate networkNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), - translatedNetworkId.get()); - Map<String, Map<String, Object>> subNetMap = (Map<String, Map<String, Object>>) networkNodeTemplate - .getProperties().get(HeatConstants.SUBNETS_PROPERTY_NAME); + NodeTemplate networkNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), translatedNetworkId.get()); + Map<String, Map<String, Object>> subNetMap = (Map<String, Map<String, Object>>) networkNodeTemplate.getProperties() + .get(HeatConstants.SUBNETS_PROPERTY_NAME); if (subNetMap == null) { subNetMap = addSubnetProperties(translateTo, networkNodeTemplate); } Map<String, Object> properties = TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getResource().getType(), networkNodeTemplate, translateTo.getContext()); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), null, translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), + translateTo.getResource().getType(), networkNodeTemplate, translateTo.getContext()); subNetMap.put(translateTo.getResourceId(), properties); } - private Map<String, Map<String, Object>> addSubnetProperties(TranslateTo translateTo, - NodeTemplate networkNodeTemplate) { + private Map<String, Map<String, Object>> addSubnetProperties(TranslateTo translateTo, NodeTemplate networkNodeTemplate) { Map<String, Map<String, Object>> subNetMap = new HashMap<>(); networkNodeTemplate.getProperties().put(HeatConstants.SUBNETS_PROPERTY_NAME, subNetMap); TranslatorHeatToToscaPropertyConverter - .setSimpleProperty(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - translateTo.getResource().getProperties(), - translateTo.getHeatFileName(), translateTo.getResource().getType(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - networkNodeTemplate.getProperties(), HeatConstants.ENABLE_DHCP_PROPERTY_NAME, - ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, networkNodeTemplate); //dhcp_enabled + .setSimpleProperty(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), translateTo.getResource().getProperties(), + translateTo.getHeatFileName(), translateTo.getResource().getType(), translateTo.getHeatOrchestrationTemplate(), + translateTo.getContext(), networkNodeTemplate.getProperties(), HeatConstants.ENABLE_DHCP_PROPERTY_NAME, + ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, networkNodeTemplate); //dhcp_enabled TranslatorHeatToToscaPropertyConverter - .setSimpleProperty(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - translateTo.getResource().getProperties(), - translateTo.getHeatFileName(), translateTo.getResource().getType(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - networkNodeTemplate.getProperties(), IP_VERSION_PROPERTY_NAME, null, networkNodeTemplate); + .setSimpleProperty(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), translateTo.getResource().getProperties(), + translateTo.getHeatFileName(), translateTo.getResource().getType(), translateTo.getHeatOrchestrationTemplate(), + translateTo.getContext(), networkNodeTemplate.getProperties(), IP_VERSION_PROPERTY_NAME, null, networkNodeTemplate); handleDhcpProperty(translateTo, networkNodeTemplate); return subNetMap; } @@ -100,8 +90,8 @@ public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBas Optional<AttachedResourceId> subnetNetwork = getAttachedNetworkResource(translateTo); if (!subnetNetwork.get().isGetResource()) { logger.warn("Heat resource: '{}' with type: '{}' include 'network_id/'network'' property without " - + "'get_resource' function, therefore this resource will be ignored in TOSCA translation.", - translateTo.getResourceId(), translateTo.getResource().getType()); + + "'get_resource' function, therefore this resource will be ignored in TOSCA translation.", translateTo.getResourceId(), + translateTo.getResource().getType()); return null; } return (String) subnetNetwork.get().getTranslatedId(); @@ -118,8 +108,7 @@ public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBas } ParameterDefinition dhcpParameterDefinition = null; if (translateTo.getServiceTemplate().getTopology_template().getInputs() != null) { - dhcpParameterDefinition = - translateTo.getServiceTemplate().getTopology_template().getInputs().get(dhcpEnabledParameterName); + dhcpParameterDefinition = translateTo.getServiceTemplate().getTopology_template().getInputs().get(dhcpEnabledParameterName); } if (dhcpParameterDefinition == null) { logger.warn("Missing input parameter : {} ", dhcpEnabledParameterName); @@ -134,29 +123,24 @@ public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBas } catch (CoreException coreException) { dhcpParameterDefinition.set_default(true); logger.warn("Parameter '{}' used for {} boolean property, but it's value is not a valid boolean " - + "value, therefore {} property will be set with default value of 'true'.", - dhcpEnabledParameterName, ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, ToscaConstants - .DHCP_ENABLED_PROPERTY_NAME, coreException); + + "value, therefore {} property will be set with default value of 'true'.", dhcpEnabledParameterName, + ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, coreException); } dhcpParameterDefinition.setType(PropertyType.BOOLEAN.getDisplayName()); } } private Optional<AttachedResourceId> getAttachedNetworkResource(TranslateTo translateTo) { - Optional<AttachedResourceId> attachedNetworkId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_ID_PROPERTY_NAME); + Optional<AttachedResourceId> attachedNetworkId = HeatToToscaUtil + .extractAttachedResourceId(translateTo, HeatConstants.NETWORK_ID_PROPERTY_NAME); if (attachedNetworkId.isPresent()) { return attachedNetworkId; } - Optional<AttachedResourceId> attachedNetwork = - HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_PROPERTY_NAME); + Optional<AttachedResourceId> attachedNetwork = HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_PROPERTY_NAME); if (attachedNetwork.isPresent()) { return attachedNetwork; } throw new CoreException( - new MissingMandatoryPropertyErrorBuilder(HeatConstants.NETWORK_ID_PROPERTY_NAME + "/" - + HeatConstants.NETWORK_PROPERTY_NAME).build()); + new MissingMandatoryPropertyErrorBuilder(HeatConstants.NETWORK_ID_PROPERTY_NAME + "/" + HeatConstants.NETWORK_PROPERTY_NAME).build()); } } - - diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java index ccd02955cd..1ad038f718 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import java.util.ArrayList; @@ -23,7 +22,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.GroupDefinition; import org.onap.sdc.tosca.datatypes.model.PolicyDefinition; @@ -37,14 +35,14 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslationBase { + private static final String AFFINITY = "affinity"; private static final String ANTI_AFFINITY = "anti-affinity"; private static final List<String> supportedPolicies = Arrays.asList(AFFINITY, ANTI_AFFINITY); @Override protected String generateTranslatedId(TranslateTo translateTo) { - return isEssentialRequirementsValid(translateTo) ? getTranslatedGroupId( - translateTo.getResourceId()) : null; + return isEssentialRequirementsValid(translateTo) ? getTranslatedGroupId(translateTo.getResourceId()) : null; } @Override @@ -53,8 +51,7 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation } @Override - protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement(TranslateTo translateTo) { if (isEssentialRequirementsValid(translateTo)) { return Optional.of(ToscaTopologyTemplateElements.GROUP); } else { @@ -64,16 +61,13 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation private boolean validatePolicyType(TranslateTo translateTo) { Map<String, Object> properties = translateTo.getResource().getProperties(); - if (Objects.isNull(properties) - || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) { + if (Objects.isNull(properties) || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) { return true; } - Object policies = properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME); if (!(policies instanceof List)) { return false; } - for (Object policy : (List) policies) { if (!isValidPolicyType(policy, translateTo.getResourceId(), translateTo.getResource())) { return false; @@ -86,14 +80,12 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation if (!(policy instanceof String)) { return false; } - if (!supportedPolicies.contains(policy)) { String unsupportedPolicy = policy.toString(); - logger.warn("Resource '{}'({}) contains unsupported policy '{}'. This resource is been ignored during " - + "the translation", resourceId, resource.getType(), unsupportedPolicy); + logger.warn("Resource '{}'({}) contains unsupported policy '{}'. This resource is been ignored during " + "the translation", resourceId, + resource.getType(), unsupportedPolicy); return false; } - return true; } @@ -107,10 +99,8 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation } } - private void addPoliciesToTopology(TranslateTo translateTo, String policyTargetEntityId, - List<String> toscaPolicyTypes) { - logger.info("******** Start creating policies for resource '%s' ********", - translateTo.getResourceId()); + private void addPoliciesToTopology(TranslateTo translateTo, String policyTargetEntityId, List<String> toscaPolicyTypes) { + logger.info("******** Start creating policies for resource '%s' ********", translateTo.getResourceId()); for (int i = 0; i < toscaPolicyTypes.size(); i++) { String policy = toscaPolicyTypes.get(i); logger.info("******** Creating policy '%s' ********", policy); @@ -118,29 +108,19 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation policyDefinition.setType(policy); policyDefinition.setTargets(Collections.singletonList(policyTargetEntityId)); policyDefinition.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - policyDefinition.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - policyDefinition, translateTo.getContext())); - policyDefinition.getProperties().put( - policy.equals(ToscaPolicyType.PLACEMENT_ANTILOCATE) ? "container_type" - : AFFINITY, "host"); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), policyDefinition.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), policyDefinition, translateTo.getContext())); + policyDefinition.getProperties().put(policy.equals(ToscaPolicyType.PLACEMENT_ANTILOCATE) ? "container_type" : AFFINITY, "host"); String policyId = getTranslatedPolicyId(translateTo, toscaPolicyTypes, i); - DataModelUtil - .addPolicyDefinition(translateTo.getServiceTemplate(), policyId, policyDefinition); + DataModelUtil.addPolicyDefinition(translateTo.getServiceTemplate(), policyId, policyDefinition); logger.info("******** Policy '%s' created ********", policy); } - - logger - .info("******** All policies for resource '%s' created successfully ********", - translateTo.getResourceId()); + logger.info("******** All policies for resource '%s' created successfully ********", translateTo.getResourceId()); } - private String getTranslatedPolicyId(TranslateTo translateTo, List<String> toscaPolicyTypes, - int policyIndex) { - return translateTo.getResourceId() + (toscaPolicyTypes.size() > 1 ? policyIndex : "") - + "_policy"; + private String getTranslatedPolicyId(TranslateTo translateTo, List<String> toscaPolicyTypes, int policyIndex) { + return translateTo.getResourceId() + (toscaPolicyTypes.size() > 1 ? policyIndex : "") + "_policy"; } private String addGroupToTopology(TranslateTo translateTo, String resourceId) { @@ -149,9 +129,7 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation group.setMembers(new ArrayList<>()); group.setType(ToscaGroupType.NATIVE_ROOT); String translatedGroupId = getTranslatedGroupId(resourceId); - DataModelUtil - .addGroupDefinitionToTopologyTemplate(translateTo.getServiceTemplate(), - translatedGroupId, group); + DataModelUtil.addGroupDefinitionToTopologyTemplate(translateTo.getServiceTemplate(), translatedGroupId, group); logger.info("******** Creating group '%s' for resource '%s' ********", resourceId, resourceId); return translatedGroupId; } @@ -162,11 +140,9 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation private List<String> getToscaPolicies(Resource resource, String resourceId) { Map<String, Object> properties = resource.getProperties(); - if (Objects.isNull(properties) - || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) { + if (Objects.isNull(properties) || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) { return Collections.singletonList(ToscaPolicyType.PLACEMENT_ANTILOCATE); } - List<Object> policies = (List) properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME); List<String> retList = new ArrayList<>(); policies.forEach(policy -> { @@ -184,5 +160,4 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation return ToscaPolicyType.PLACEMENT_ANTILOCATE; } } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java index 71dfeb9f53..a934f00aa0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.heat.services.HeatConstants.SNAPSHOT_ID_PROPERTY_NAME; @@ -27,16 +26,15 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; +import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; import org.onap.sdc.tosca.datatypes.model.GroupDefinition; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RelationshipTemplate; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; -import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; import org.openecomp.sdc.heat.datatypes.HeatBoolean; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -66,11 +64,11 @@ import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFact import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { + private static final Logger logger = LoggerFactory.getLogger(ResourceTranslationNovaServerImpl.class); private static final String BLOCK_DEVICE_MAPPING_DEVICE_NAME = "device_name"; private static final String VOL_ATTACH_DEVICE_PROPERTY_NAME = "device"; private static final String FABRIC_CONFIGURATION_KEY = "fabric_configuration_monitoring"; - @Override protected void translate(TranslateTo translateTo) { @@ -78,52 +76,39 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { Map<String, Object> properties = translateTo.getResource().getProperties(); String heatFileName = translateTo.getHeatFileName(); ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); - String nodeTypeRef = createLocalNodeType(serviceTemplate, translateTo.getResource(), - translateTo.getResourceId(), translateTo.getTranslatedId()); + String nodeTypeRef = createLocalNodeType(serviceTemplate, translateTo.getResource(), translateTo.getResourceId(), + translateTo.getTranslatedId()); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - - context.getComputeConsolidationDataHandler().addConsolidationData( - serviceTemplateFileName, nodeTypeRef, translateTo.getTranslatedId()); - + context.getComputeConsolidationDataHandler().addConsolidationData(serviceTemplateFileName, nodeTypeRef, translateTo.getTranslatedId()); NodeTemplate novaNodeTemplate = new NodeTemplate(); novaNodeTemplate.setType(nodeTypeRef); - HeatOrchestrationTemplate heatOrchestrationTemplate = - translateTo.getHeatOrchestrationTemplate(); + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo.getHeatOrchestrationTemplate(); novaNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(serviceTemplate, translateTo.getResourceId(), - properties, novaNodeTemplate.getProperties(), heatFileName, - heatOrchestrationTemplate, translateTo.getResource().getType(), - novaNodeTemplate, context)); - HeatToToscaUtil.mapBoolean(novaNodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.CONFIG_DRIVE_PROPERTY_NAME)); + .getToscaPropertiesSimpleConversion(serviceTemplate, translateTo.getResourceId(), properties, novaNodeTemplate.getProperties(), + heatFileName, heatOrchestrationTemplate, translateTo.getResource().getType(), novaNodeTemplate, context)); + HeatToToscaUtil.mapBoolean(novaNodeTemplate, HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.CONFIG_DRIVE_PROPERTY_NAME)); manageNovaServerNetwork(translateTo, novaNodeTemplate); manageNovaServerBlockDeviceMapping(translateTo, novaNodeTemplate); manageNovaServerGroupMapping(translateTo, novaNodeTemplate); DataModelUtil.addNodeTemplate(serviceTemplate, translateTo.getTranslatedId(), novaNodeTemplate); } - private void manageNovaServerGroupMapping(TranslateTo translateTo, - NodeTemplate novaNodeTemplate) { + private void manageNovaServerGroupMapping(TranslateTo translateTo, NodeTemplate novaNodeTemplate) { Map properties = translateTo.getResource().getProperties(); if (isSchedulerHintsPropExist(properties)) { Object schedulerHints = properties.get(ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction()); if (schedulerHints instanceof Map) { - addServerGroupHintsToPoliciesGroups(translateTo, - novaNodeTemplate, (Map) schedulerHints); + addServerGroupHintsToPoliciesGroups(translateTo, novaNodeTemplate, (Map) schedulerHints); } else { - logger.warn("'scheduler_hints' property of resource '{}' is not valid. This property should be a map", - translateTo.getResourceId()); + logger.warn("'scheduler_hints' property of resource '{}' is not valid. This property should be a map", translateTo.getResourceId()); } } } - private void addServerGroupHintsToPoliciesGroups(TranslateTo translateTo, - NodeTemplate novaNodeTemplate, - Map schedulerHints) { + private void addServerGroupHintsToPoliciesGroups(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Map schedulerHints) { for (Object hint : schedulerHints.values()) { Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo - .getHeatOrchestrationTemplate(), translateTo.getContext(), hint); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), hint); if (attachedResourceId.isPresent()) { AttachedResourceId serverGroupResourceId = attachedResourceId.get(); Object serverGroupResourceToTranslate = serverGroupResourceId.getEntityId(); @@ -136,77 +121,59 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { } } - private void addServerGroupHintGetParam(TranslateTo translateTo, NodeTemplate novaNodeTemplate, - Object serverGroupResourceToTranslate) { - TranslatedHeatResource translatedServerGroupResource = translateTo.getContext() - .getHeatSharedResourcesByParam().get(serverGroupResourceToTranslate); - if (Objects.nonNull(translatedServerGroupResource) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName()) - && isResourceTypeServerGroup(translatedServerGroupResource)) { - Map<String, GroupDefinition> groups = - translateTo.getServiceTemplate().getTopology_template().getGroups(); - if (MapUtils.isNotEmpty(groups) && Objects.nonNull(groups.get(translatedServerGroupResource - .getTranslatedId()))) { - groups.get(translatedServerGroupResource.getTranslatedId()).getMembers() - .add(translateTo.getTranslatedId()); + private void addServerGroupHintGetParam(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Object serverGroupResourceToTranslate) { + TranslatedHeatResource translatedServerGroupResource = translateTo.getContext().getHeatSharedResourcesByParam() + .get(serverGroupResourceToTranslate); + if (Objects.nonNull(translatedServerGroupResource) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName()) + && isResourceTypeServerGroup(translatedServerGroupResource)) { + Map<String, GroupDefinition> groups = translateTo.getServiceTemplate().getTopology_template().getGroups(); + if (MapUtils.isNotEmpty(groups) && Objects.nonNull(groups.get(translatedServerGroupResource.getTranslatedId()))) { + groups.get(translatedServerGroupResource.getTranslatedId()).getMembers().add(translateTo.getTranslatedId()); //Add group Id to compute consolidation data - updateComputeConsolidationDataGroup(translateTo, novaNodeTemplate, - translatedServerGroupResource.getTranslatedId()); + updateComputeConsolidationDataGroup(translateTo, novaNodeTemplate, translatedServerGroupResource.getTranslatedId()); } } } - private void addServerGroupHintGetResource(TranslateTo translateTo, NodeTemplate novaNodeTemplate, - Object serverGroupResourceToTranslate) { - boolean isHintOfTypeNovaServerGroup = isHintOfTypeNovaServerGroup(translateTo - .getHeatOrchestrationTemplate(), serverGroupResourceToTranslate); + private void addServerGroupHintGetResource(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Object serverGroupResourceToTranslate) { + boolean isHintOfTypeNovaServerGroup = isHintOfTypeNovaServerGroup(translateTo.getHeatOrchestrationTemplate(), serverGroupResourceToTranslate); if (isHintOfTypeNovaServerGroup) { addNovaServerToPolicyGroup(translateTo, (String) serverGroupResourceToTranslate, novaNodeTemplate); } } private boolean isResourceTypeServerGroup(TranslatedHeatResource translatedServerGroupResource) { - return translatedServerGroupResource.getHeatResource().getType() - .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); + return translatedServerGroupResource.getHeatResource().getType().equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); } - private void updateComputeConsolidationDataGroup(TranslateTo translateTo, - NodeTemplate novaNodeTemplate, String groupId) { + private void updateComputeConsolidationDataGroup(TranslateTo translateTo, NodeTemplate novaNodeTemplate, String groupId) { ComputeConsolidationDataHandler handler = translateTo.getContext().getComputeConsolidationDataHandler(); - handler.addGroupIdToConsolidationData(translateTo,novaNodeTemplate.getType(), - translateTo.getTranslatedId(), groupId); + handler.addGroupIdToConsolidationData(translateTo, novaNodeTemplate.getType(), translateTo.getTranslatedId(), groupId); } - private boolean isHintOfTypeNovaServerGroup(HeatOrchestrationTemplate heatOrchestrationTemplate, - Object resourceToTranslate) { + private boolean isHintOfTypeNovaServerGroup(HeatOrchestrationTemplate heatOrchestrationTemplate, Object resourceToTranslate) { return heatOrchestrationTemplate.getResources().get(resourceToTranslate).getType() - .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); + .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); } - private void addNovaServerToPolicyGroup(TranslateTo translateTo, - String resourceToTranslate, - NodeTemplate novaNodeTemplate) { - Resource serverGroup = - HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), resourceToTranslate, - translateTo.getHeatFileName()); + private void addNovaServerToPolicyGroup(TranslateTo translateTo, String resourceToTranslate, NodeTemplate novaNodeTemplate) { + Resource serverGroup = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), resourceToTranslate, translateTo.getHeatFileName()); Optional<String> serverGroupTranslatedId = ResourceTranslationFactory.getInstance(serverGroup) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), serverGroup, resourceToTranslate, - translateTo.getContext()); + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + serverGroup, resourceToTranslate, translateTo.getContext()); if (serverGroupTranslatedId.isPresent()) { - translateTo.getServiceTemplate().getTopology_template().getGroups().get(serverGroupTranslatedId.get()) - .getMembers().add(translateTo.getTranslatedId()); + translateTo.getServiceTemplate().getTopology_template().getGroups().get(serverGroupTranslatedId.get()).getMembers() + .add(translateTo.getTranslatedId()); updateComputeConsolidationDataGroup(translateTo, novaNodeTemplate, serverGroupTranslatedId.get()); } } private boolean isSchedulerHintsPropExist(Map properties) { - return !MapUtils.isEmpty(properties) - && Objects.nonNull(properties.get(ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction())); + return !MapUtils.isEmpty(properties) && Objects.nonNull(properties.get(ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction())); } - private void manageNovaServerBlockDeviceMapping(TranslateTo translateTo, - NodeTemplate novaNodeTemplate) { + private void manageNovaServerBlockDeviceMapping(TranslateTo translateTo, NodeTemplate novaNodeTemplate) { Resource resource = translateTo.getResource(); List<Map<String, Object>> blockDeviceMappingList = getBlockDeviceMappingList(resource); if (CollectionUtils.isEmpty(blockDeviceMappingList)) { @@ -219,20 +186,17 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { } private int connectBlockDeviceToNovaServer(TranslateTo translateTo, NodeTemplate novaNodeTemplate, int index, - Map<String, Object> blockDeviceMapping) { + Map<String, Object> blockDeviceMapping) { Object volumeIdObject = blockDeviceMapping.get(VOL_ID_PROPERTY_NAME); Object snapshotIdObject = blockDeviceMapping.get(SNAPSHOT_ID_PROPERTY_NAME); - if (volumeIdObject == null && snapshotIdObject == null) { logger.warn("Resource '{}' has block_device_mapping property with empty/missing volume_id and snapshot_id " - + "properties. Entry number {}, this entry will be ignored in TOSCA translation.", - translateTo.getResourceId(), (index + 1)); + + "properties. Entry number {}, this entry will be ignored in TOSCA translation.", translateTo.getResourceId(), (index + 1)); index++; return index; } if (volumeIdObject == null) { - connectBlockDeviceUsingSnapshotId(translateTo, novaNodeTemplate, snapshotIdObject, index, - blockDeviceMapping); + connectBlockDeviceUsingSnapshotId(translateTo, novaNodeTemplate, snapshotIdObject, index, blockDeviceMapping); } else { connectBlockDeviceUsingVolumeId(translateTo, novaNodeTemplate, volumeIdObject); } @@ -240,72 +204,60 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { return index; } - private void connectBlockDeviceUsingVolumeId(TranslateTo translateTo, NodeTemplate novaNodeTemplate, - Object volumeIdObject) { + private void connectBlockDeviceUsingVolumeId(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Object volumeIdObject) { Optional<AttachedResourceId> attachedVolumeId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getContext(), volumeIdObject); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + volumeIdObject); if (attachedVolumeId.isPresent() && attachedVolumeId.get().isGetResource()) { - connectNovaServerToVolume(novaNodeTemplate, (String) attachedVolumeId.get().getTranslatedId(), null, - translateTo); + connectNovaServerToVolume(novaNodeTemplate, (String) attachedVolumeId.get().getTranslatedId(), null, translateTo); } } - private void connectBlockDeviceUsingSnapshotId(TranslateTo translateTo, NodeTemplate novaNodeTemplate, - Object snapshotIdObject, int index, - Map<String, Object> blockDeviceMapping) { + private void connectBlockDeviceUsingSnapshotId(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Object snapshotIdObject, int index, + Map<String, Object> blockDeviceMapping) { String novaServerTranslatedId = translateTo.getTranslatedId(); String volumeResourceId; Optional<AttachedResourceId> attachedSnapshotId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getContext(), snapshotIdObject); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + snapshotIdObject); if (attachedSnapshotId.isPresent()) { volumeResourceId = novaServerTranslatedId + "_" + attachedSnapshotId.get().getEntityId(); String deviceName = (String) blockDeviceMapping.get(BLOCK_DEVICE_MAPPING_DEVICE_NAME); String relationshipId = novaServerTranslatedId + "_" + index; - createVolumeAttachesToRelationship(translateTo.getServiceTemplate(), deviceName, novaServerTranslatedId, - volumeResourceId, relationshipId); + createVolumeAttachesToRelationship(translateTo.getServiceTemplate(), deviceName, novaServerTranslatedId, volumeResourceId, + relationshipId); createCinderVolumeNodeTemplate(translateTo, volumeResourceId, blockDeviceMapping); - connectNovaServerToVolume(novaNodeTemplate, volumeResourceId, relationshipId, - translateTo); + connectNovaServerToVolume(novaNodeTemplate, volumeResourceId, relationshipId, translateTo); } } - private void connectNovaServerToVolume(NodeTemplate novaNodeTemplate, String volumeResourceId, - String relationshipId, TranslateTo translateTo) { + private void connectNovaServerToVolume(NodeTemplate novaNodeTemplate, String volumeResourceId, String relationshipId, TranslateTo translateTo) { RequirementAssignment requirementAssignment = new RequirementAssignment(); requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); requirementAssignment.setNode(volumeResourceId); if (relationshipId != null) { requirementAssignment.setRelationship(relationshipId); } else { - requirementAssignment - .setRelationship(ToscaRelationshipType.NATIVE_ATTACHES_TO); + requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_ATTACHES_TO); } - DataModelUtil.addRequirementAssignment(novaNodeTemplate, ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, - requirementAssignment); + DataModelUtil.addRequirementAssignment(novaNodeTemplate, ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirementAssignment); //Add volume consolidation data - ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, novaNodeTemplate.getType(), - translateTo.getTranslatedId(), ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirementAssignment); + ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, novaNodeTemplate.getType(), translateTo.getTranslatedId(), + ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirementAssignment); } - private void createCinderVolumeNodeTemplate(TranslateTo translateTo, - String volumeResourceId, - Map<String, Object> blockDeviceMapping) { + private void createCinderVolumeNodeTemplate(TranslateTo translateTo, String volumeResourceId, Map<String, Object> blockDeviceMapping) { NodeTemplate cinderVolumeNodeTemplate = new NodeTemplate(); cinderVolumeNodeTemplate.setType(ToscaNodeType.CINDER_VOLUME); cinderVolumeNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), - blockDeviceMapping, null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - cinderVolumeNodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), blockDeviceMapping, null, + translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), cinderVolumeNodeTemplate, translateTo.getContext())); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), volumeResourceId, cinderVolumeNodeTemplate); } - private void createVolumeAttachesToRelationship(ServiceTemplate serviceTemplate, - String deviceName, String novaServerTranslatedId, - String volumeId, String relationshipId) { + private void createVolumeAttachesToRelationship(ServiceTemplate serviceTemplate, String deviceName, String novaServerTranslatedId, + String volumeId, String relationshipId) { RelationshipTemplate relationshipTemplate = new RelationshipTemplate(); relationshipTemplate.setType(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO); Map<String, Object> properties = new HashMap<>(); @@ -322,29 +274,23 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { if (Objects.isNull(resource.getProperties())) { return Collections.emptyList(); } - List<Map<String, Object>> blockDeviceMappingList = - (List<Map<String, Object>>) resource.getProperties().get(HeatConstants.BLOCK_DEVICE_MAPPING); - List<Map<String, Object>> blockDeviceMappingV2List = - (List<Map<String, Object>>) resource.getProperties().get(HeatConstants.BLOCK_DEVICE_MAPPING_V2); - + List<Map<String, Object>> blockDeviceMappingList = (List<Map<String, Object>>) resource.getProperties() + .get(HeatConstants.BLOCK_DEVICE_MAPPING); + List<Map<String, Object>> blockDeviceMappingV2List = (List<Map<String, Object>>) resource.getProperties() + .get(HeatConstants.BLOCK_DEVICE_MAPPING_V2); if (blockDeviceMappingList != null && blockDeviceMappingV2List != null) { blockDeviceMappingList.addAll(blockDeviceMappingV2List); - } else if (CollectionUtils.isEmpty(blockDeviceMappingList) - && CollectionUtils.isEmpty(blockDeviceMappingV2List)) { + } else if (CollectionUtils.isEmpty(blockDeviceMappingList) && CollectionUtils.isEmpty(blockDeviceMappingV2List)) { return Collections.emptyList(); - } else { - blockDeviceMappingList = - blockDeviceMappingList != null ? blockDeviceMappingList : blockDeviceMappingV2List; + blockDeviceMappingList = blockDeviceMappingList != null ? blockDeviceMappingList : blockDeviceMappingV2List; } return blockDeviceMappingList; } - private void manageNovaServerNetwork(TranslateTo translateTo, - NodeTemplate novaNodeTemplate) { + private void manageNovaServerNetwork(TranslateTo translateTo, NodeTemplate novaNodeTemplate) { Resource resource = translateTo.getResource(); String translatedId = translateTo.getTranslatedId(); - if (resource.getProperties() == null) { return; } @@ -352,30 +298,22 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { if (Objects.isNull(networks) || !(networks instanceof List)) { return; } - List<Map<String, Object>> heatNetworkList = (List<Map<String, Object>>) networks; - - for (Map<String, Object> heatNetwork : heatNetworkList) { - - Optional<Resource> portResourceOp = getOrTranslatePortTemplate(translateTo, heatNetwork.get( - Constants.PORT_PROPERTY_NAME), translatedId, novaNodeTemplate); + Optional<Resource> portResourceOp = getOrTranslatePortTemplate(translateTo, heatNetwork.get(Constants.PORT_PROPERTY_NAME), translatedId, + novaNodeTemplate); portResourceOp.ifPresent(portResource -> handleFabricConfiguration(translateTo, novaNodeTemplate.getType(), portResource)); } - - } - - private void handleFabricConfiguration(TranslateTo translateTo, String resourceType, Resource portResource ){ - - Optional<Object> valueSpacesProperty = HeatToToscaUtil.getResourceProperty(portResource, HeatConstants.VALUE_SPECS_PROPERTY_NAME); - - valueSpacesProperty.filter(props -> props instanceof Map && MapUtils.isNotEmpty((Map)props)).ifPresent(valueSpecs ->{ - if(valueSpecs instanceof Map && (isAttFabricConfigurationFlagSet((Map)valueSpecs) || isBindingProfileFabricConfigSet((Map)valueSpecs))) { - addFabricConfigurationCapability(translateTo, resourceType); - } - - }); - + } + + private void handleFabricConfiguration(TranslateTo translateTo, String resourceType, Resource portResource) { + Optional<Object> valueSpacesProperty = HeatToToscaUtil.getResourceProperty(portResource, HeatConstants.VALUE_SPECS_PROPERTY_NAME); + valueSpacesProperty.filter(props -> props instanceof Map && MapUtils.isNotEmpty((Map) props)).ifPresent(valueSpecs -> { + if (valueSpecs instanceof Map && (isAttFabricConfigurationFlagSet((Map) valueSpecs) || isBindingProfileFabricConfigSet( + (Map) valueSpecs))) { + addFabricConfigurationCapability(translateTo, resourceType); + } + }); } private boolean isValueFoundAndTrue(Object value) { @@ -389,48 +327,44 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { private boolean isBindingProfileFabricConfigSet(Map valueSpecs) { Object binding_profile = valueSpecs.get(HeatConstants.VALUE_SPECS_BINDING_PROFILE_PROPERTY_NAME); if (Objects.nonNull(binding_profile) && binding_profile instanceof Map) { - return !MapUtils.isEmpty((Map)binding_profile) - && isValueFoundAndTrue(((Map)binding_profile).get(HeatConstants.VALUE_SPECS_FABRIC_CONFIG_PROPERTY_NAME)); + return !MapUtils.isEmpty((Map) binding_profile) && isValueFoundAndTrue( + ((Map) binding_profile).get(HeatConstants.VALUE_SPECS_FABRIC_CONFIG_PROPERTY_NAME)); } return false; } - - private void addFabricConfigurationCapability(TranslateTo translateTo, String localType){ - + + private void addFabricConfigurationCapability(TranslateTo translateTo, String localType) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); Map<String, CapabilityDefinition> mapCapabilities = new HashMap<>(); - CapabilityDefinition fabricConfigurationCap = new CapabilityDefinition(); + CapabilityDefinition fabricConfigurationCap = new CapabilityDefinition(); fabricConfigurationCap.setType(ToscaCapabilityType.FABRIC_CONFIGURATION); mapCapabilities.put(FABRIC_CONFIGURATION_KEY, fabricConfigurationCap); - DataModelUtil.addNodeTypeCapabilitiesDef (DataModelUtil.getNodeType(serviceTemplate, localType), mapCapabilities); + DataModelUtil.addNodeTypeCapabilitiesDef(DataModelUtil.getNodeType(serviceTemplate, localType), mapCapabilities); if (logger.isDebugEnabled()) { - logger.debug("New capability of type {} will be added to resource {}", ToscaCapabilityType.FABRIC_CONFIGURATION, translateTo.getResourceId()); + logger.debug("New capability of type {} will be added to resource {}", ToscaCapabilityType.FABRIC_CONFIGURATION, + translateTo.getResourceId()); } } - private Optional<Resource> getOrTranslatePortTemplate(TranslateTo translateTo, - Object port, - String novaServerResourceId, - NodeTemplate novaNodeTemplate) { + private Optional<Resource> getOrTranslatePortTemplate(TranslateTo translateTo, Object port, String novaServerResourceId, + NodeTemplate novaNodeTemplate) { String heatFileName = translateTo.getHeatFileName(); HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo.getHeatOrchestrationTemplate(); TranslationContext context = translateTo.getContext(); Optional<AttachedResourceId> attachedPortId = HeatToToscaUtil - .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, port); + .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, port); if (!attachedPortId.isPresent() || !attachedPortId.get().isGetResource()) { return Optional.empty(); } String resourceId = (String) attachedPortId.get().getEntityId(); Resource portResource = HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName); if (!isSupportedPortResource(portResource)) { - logger.warn("NovaServer connect to port resource with id : {} and type : {}. This resource type is " - + "not " + "supported, therefore the connection to the port is ignored. " - + "Supported types are: {}, {}", resourceId, portResource.getType(), - HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); + logger.warn("NovaServer connect to port resource with id : {} and type : {}. This resource type is " + "not " + + "supported, therefore the connection to the port is ignored. " + "Supported types are: {}, {}", resourceId, portResource.getType(), + HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); return Optional.empty(); - } else if (HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE - .getHeatResource().equals(portResource.getType())) { + } else if (HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource().equals(portResource.getType())) { Map<String, Object> properties = portResource.getProperties(); if (!MapUtils.isEmpty(properties) && Objects.nonNull(properties.get(HeatConstants.PORT_TUPLE_REFS))) { novaNodeTemplate.getProperties().put(ToscaConstants.CONTRAIL_SERVICE_INSTANCE_IND, true); @@ -438,19 +372,16 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { } ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); Optional<String> translatedPortId = ResourceTranslationFactory.getInstance(portResource) - .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, portResource, - resourceId, context); + .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, portResource, resourceId, context); if (translatedPortId.isPresent()) { - NodeTemplate portNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, translatedPortId.get()); + NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, translatedPortId.get()); DataModelUtil.addBindingReqFromPortToCompute(novaServerResourceId, portNodeTemplate); // Add ports - ConsolidationDataUtil.updatePortInConsolidationData(translateTo, novaNodeTemplate.getType(), resourceId, - portResource.getType(), translatedPortId.get()); + ConsolidationDataUtil + .updatePortInConsolidationData(translateTo, novaNodeTemplate.getType(), resourceId, portResource.getType(), translatedPortId.get()); } else { logger.warn("NovaServer connect to port resource with id : {} and type : {}. This resource type" - + " is not supported, therefore the connection to the port is ignored.", resourceId, - portResource.getType()); + + " is not supported, therefore the connection to the port is ignored.", resourceId, portResource.getType()); return Optional.empty(); } return Optional.ofNullable(portResource); @@ -458,17 +389,12 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { private boolean isSupportedPortResource(Resource portResource) { return Arrays.asList(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()) - .contains(portResource.getType()); + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()).contains(portResource.getType()); } - - private String createLocalNodeType(ServiceTemplate serviceTemplate, Resource resource, - String resourceId, String translatedId) { + private String createLocalNodeType(ServiceTemplate serviceTemplate, Resource resource, String resourceId, String translatedId) { NameExtractor nodeTypeNameExtractor = TranslationContext.getNameExtractorImpl(resource.getType()); - String nodeTypeName = - nodeTypeNameExtractor.extractNodeTypeName(resource, resourceId, translatedId); - + String nodeTypeName = nodeTypeNameExtractor.extractNodeTypeName(resource, resourceId, translatedId); if (!isNodeTypeCreated(serviceTemplate, nodeTypeName)) { DataModelUtil.addNodeType(serviceTemplate, nodeTypeName, createNodeType()); } @@ -478,26 +404,19 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { /** * Get property Regex matcher list. * - * @return Regex expression per nova resource property, while nova node type name is consider when - * setting the name value. + * @return Regex expression per nova resource property, while nova node type name is consider when setting the name value. */ public List<PropertyRegexMatcher> getPropertyRegexMatchersForNovaNodeType() { List<PropertyRegexMatcher> propertyRegexMatchers = new ArrayList<>(3); propertyRegexMatchers - .add(new PropertyRegexMatcher(Constants.NAME_PROPERTY_NAME, - Arrays.asList(".+_name$", ".+_names$", ".+_name_[0-9]+"), "_name")); - propertyRegexMatchers - .add(new PropertyRegexMatcher("image", Collections.singletonList(".+_image_name$"), - "_image_name")); - propertyRegexMatchers - .add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), - "_flavor_name")); + .add(new PropertyRegexMatcher(Constants.NAME_PROPERTY_NAME, Arrays.asList(".+_name$", ".+_names$", ".+_name_[0-9]+"), "_name")); + propertyRegexMatchers.add(new PropertyRegexMatcher("image", Collections.singletonList(".+_image_name$"), "_image_name")); + propertyRegexMatchers.add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), "_flavor_name")); return propertyRegexMatchers; } private boolean isNodeTypeCreated(ServiceTemplate serviceTemplate, String nodeTypeName) { - return !MapUtils.isEmpty(serviceTemplate.getNode_types()) - && Objects.nonNull(serviceTemplate.getNode_types().get(nodeTypeName)); + return !MapUtils.isEmpty(serviceTemplate.getNode_types()) && Objects.nonNull(serviceTemplate.getNode_types().get(nodeTypeName)); } private NodeType createNodeType() { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java index 779550e99d..d976434e06 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.heat.services.HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME; @@ -25,7 +24,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -48,61 +46,51 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas @Override protected void translate(TranslateTo translateTo) { final String heatFileName = translateTo.getHeatFileName(); - Object resourceDef = - translateTo.getResource().getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); + Object resourceDef = translateTo.getResource().getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); Resource nestedResource = new Resource(); Object typeDefinition = ((Map) resourceDef).get(RESOURCE_DEF_TYPE_PROPERTY_NAME); if (!(typeDefinition instanceof String)) { logger.warn("Resource '{}' of type '{}' with resourceDef which is not pointing to nested heat file is not" - + " supported and will be ignored in the translation ", translateTo.getResourceId(), - HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()); + + " supported and will be ignored in the translation ", translateTo.getResourceId(), + HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()); return; } String type = (String) typeDefinition; if (!HeatToToscaUtil.isYmlFileType(type)) { logger.warn("Resource '{}' of type '{}' with resourceDef which is not pointing to nested heat file is not" - + " supported and will be ignored in the translation ", translateTo.getResourceId(), - HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()); + + " supported and will be ignored in the translation ", translateTo.getResourceId(), + HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()); return; } - nestedResource.setType(type); - nestedResource.setProperties((Map<String, Object>) ((Map) resourceDef).get(HeatConstants - .RESOURCE_DEF_PROPERTIES)); + nestedResource.setProperties((Map<String, Object>) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_PROPERTIES)); nestedResource.setMetadata(((Map) resourceDef).get(NESTED_RESOURCE_METADATA)); - - Optional<String> substitutionNodeTemplateId = - ResourceTranslationFactory.getInstance(nestedResource) - .translateResource(heatFileName, translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), nestedResource, - translateTo.getResourceId(), translateTo.getContext()); - - substitutionNodeTemplateId.ifPresent(nodeTemplateId -> addSubstitutionNodeTemplate(translateTo, - nodeTemplateId)); + Optional<String> substitutionNodeTemplateId = ResourceTranslationFactory.getInstance(nestedResource) + .translateResource(heatFileName, translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), nestedResource, + translateTo.getResourceId(), translateTo.getContext()); + substitutionNodeTemplateId.ifPresent(nodeTemplateId -> addSubstitutionNodeTemplate(translateTo, nodeTemplateId)); } private void addSubstitutionNodeTemplate(TranslateTo translateTo, String substitutionNodeTemplateId) { - NodeTemplate substitutionNodeTemplate = - DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId); + NodeTemplate substitutionNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId); if (Objects.isNull(substitutionNodeTemplate)) { return; } - Map<String, Object> serviceTemplateFilter = (Map<String, Object>) substitutionNodeTemplate - .getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + Map<String, Object> serviceTemplateFilter = (Map<String, Object>) substitutionNodeTemplate.getProperties() + .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); populateServiceTemplateFilterProperties(translateTo, substitutionNodeTemplate, serviceTemplateFilter); handlingIndexVar(translateTo, substitutionNodeTemplate); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId, - substitutionNodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId, substitutionNodeTemplate); } private void handlingIndexVar(TranslateTo translateTo, NodeTemplate substitutionNodeTemplate) { List<String> indexVarProperties = new ArrayList<>(); String indexVarValue = getIndexVarValue(translateTo); - replacePropertiesIndexVarValue(indexVarValue, substitutionNodeTemplate.getProperties(), indexVarProperties, - translateTo); + replacePropertiesIndexVarValue(indexVarValue, substitutionNodeTemplate.getProperties(), indexVarProperties, translateTo); //Add index var properties to context for unified model later - translateTo.getContext().addIndexVarProperties(ToscaUtil.getServiceTemplateFileName(translateTo - .getServiceTemplate()), translateTo.getTranslatedId(), indexVarProperties); + translateTo.getContext() + .addIndexVarProperties(ToscaUtil.getServiceTemplateFileName(translateTo.getServiceTemplate()), translateTo.getTranslatedId(), + indexVarProperties); } private Map<String, List<String>> getNewIndexVarValue() { @@ -115,55 +103,47 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas return newIndexVarValue; } - private void replacePropertiesIndexVarValue(String indexVarValue, - Map<String, Object> properties, - List<String> indexVarProperties, + private void replacePropertiesIndexVarValue(String indexVarValue, Map<String, Object> properties, List<String> indexVarProperties, TranslateTo translateTo) { if (properties == null || properties.isEmpty()) { return; } - for (Map.Entry<String, Object> propertyEntry : properties.entrySet()) { Object propertyValue = propertyEntry.getValue(); if (propertyValue != null && propertyValue.equals(RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE)) { indexVarProperties.add(propertyEntry.getKey()); } - Object newPropertyValue = getUpdatedPropertyValueWithIndex(indexVarValue, propertyValue, - indexVarProperties, translateTo); + Object newPropertyValue = getUpdatedPropertyValueWithIndex(indexVarValue, propertyValue, indexVarProperties, translateTo); if (newPropertyValue != null) { properties.put(propertyEntry.getKey(), newPropertyValue); } } } - private Object getUpdatedPropertyValueWithIndex(String indexVarValue, Object propertyValue, - List<String> indexVarProperties, + private Object getUpdatedPropertyValueWithIndex(String indexVarValue, Object propertyValue, List<String> indexVarProperties, TranslateTo translateTo) { if (propertyValue instanceof String) { return handleStringPropertyValueWithIndex(indexVarValue, propertyValue); } else if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { return handleMapPropertyValueWithIndex(indexVarValue, propertyValue, indexVarProperties, translateTo); } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { - return handleListPropertyValueWithIndex(indexVarValue, (List) propertyValue, indexVarProperties, - translateTo); + return handleListPropertyValueWithIndex(indexVarValue, (List) propertyValue, indexVarProperties, translateTo); } return propertyValue; } - private Object handleListPropertyValueWithIndex(String indexVarValue, List propertyValue, - List<String> indexVarProperties, TranslateTo translateTo) { + private Object handleListPropertyValueWithIndex(String indexVarValue, List propertyValue, List<String> indexVarProperties, + TranslateTo translateTo) { List<Object> newPropertyValueList = new ArrayList<>(); for (Object entry : propertyValue) { - newPropertyValueList.add(getUpdatedPropertyValueWithIndex(indexVarValue, entry, - indexVarProperties, translateTo)); + newPropertyValueList.add(getUpdatedPropertyValueWithIndex(indexVarValue, entry, indexVarProperties, translateTo)); } return newPropertyValueList; } - private Object handleMapPropertyValueWithIndex(String indexVarValue, Object propertyValue, - List<String> indexVarProperties, TranslateTo translateTo) { - replacePropertiesIndexVarValue(indexVarValue, (Map<String, Object>) propertyValue, indexVarProperties, - translateTo); + private Object handleMapPropertyValueWithIndex(String indexVarValue, Object propertyValue, List<String> indexVarProperties, + TranslateTo translateTo) { + replacePropertiesIndexVarValue(indexVarValue, (Map<String, Object>) propertyValue, indexVarProperties, translateTo); return propertyValue; } @@ -175,7 +155,6 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas Map<String, List<Object>> concatMap = new HashMap<>(); List<Object> concatList = new ArrayList<>(); String value = (String) propertyValue; - while (value.contains(indexVarValue)) { if (value.indexOf(indexVarValue) == 0) { concatList.add(getNewIndexVarValue()); @@ -189,7 +168,6 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas if (!value.isEmpty()) { concatList.add(value); } - concatMap.put(ToscaFunctions.CONCAT.getFunctionName(), concatList); return concatMap; } @@ -201,26 +179,19 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas if (indexVar == null) { return HeatConstants.RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE; } - if (indexVar instanceof String) { return (String) indexVar; } - throw new CoreException( - new InvalidPropertyValueErrorBuilder(HeatConstants.INDEX_PROPERTY_NAME, - indexVar.toString(), "String").build()); + throw new CoreException(new InvalidPropertyValueErrorBuilder(HeatConstants.INDEX_PROPERTY_NAME, indexVar.toString(), "String").build()); } - private void populateServiceTemplateFilterProperties(TranslateTo translateTo, - NodeTemplate substitutionNodeTemplate, + private void populateServiceTemplateFilterProperties(TranslateTo translateTo, NodeTemplate substitutionNodeTemplate, Map<String, Object> serviceTemplateFilter) { boolean mandatory = false; Object countValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getResourceId(), - ToscaConstants.COUNT_PROPERTY_NAME, translateTo.getResource().getProperties() - .get(ToscaConstants.COUNT_PROPERTY_NAME), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - substitutionNodeTemplate, translateTo.getContext()); - + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getResourceId(), ToscaConstants.COUNT_PROPERTY_NAME, + translateTo.getResource().getProperties().get(ToscaConstants.COUNT_PROPERTY_NAME), null, translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), substitutionNodeTemplate, translateTo.getContext()); if (countValue != null) { serviceTemplateFilter.put(ToscaConstants.COUNT_PROPERTY_NAME, countValue); } else { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java index 7573374b65..93cd1c4156 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_SECURITY_RULE_PORT_CAPABILITY_CONNECTION; @@ -24,7 +23,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; - import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; @@ -42,13 +40,11 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; - class SecurityRulesToPortResourceConnection extends ResourceConnectionUsingCapabilityHelper { - SecurityRulesToPortResourceConnection(ResourceTranslationNestedImpl resourceTranslationNested, - TranslateTo translateTo, FileData nestedFileData, + + SecurityRulesToPortResourceConnection(ResourceTranslationNestedImpl resourceTranslationNested, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - super(resourceTranslationNested, translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); + super(resourceTranslationNested, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @Override @@ -64,31 +60,22 @@ class SecurityRulesToPortResourceConnection extends ResourceConnectionUsingCapab } @Override - protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { - - - Object securityGroups = - heatResource.getProperties().get(Constants.SECURITY_GROUPS_PROPERTY_NAME); + Object securityGroups = heatResource.getProperties().get(Constants.SECURITY_GROUPS_PROPERTY_NAME); List<String> paramsList = new ArrayList<>(); if (securityGroups instanceof List) { ((List) securityGroups).forEach(group -> { Optional<AttachedResourceId> attachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), group); - if (attachedResourceId.isPresent() - && attachedResourceId.get().isGetParam() - && attachedResourceId.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translateTo.getContext(), group); + if (attachedResourceId.isPresent() && attachedResourceId.get().isGetParam() && attachedResourceId.get() + .getEntityId() instanceof String) { paramsList.add((String) attachedResourceId.get().getEntityId()); } }); - return Optional.of(paramsList); } - return Optional.empty(); } @@ -98,45 +85,30 @@ class SecurityRulesToPortResourceConnection extends ResourceConnectionUsingCapab } @Override - void addRequirementToConnectResources( - Map.Entry<String, CapabilityDefinition> connectionPointEntry, List<String> paramNames) { - - + void addRequirementToConnectResources(Map.Entry<String, CapabilityDefinition> connectionPointEntry, List<String> paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } List<String> supportedSecurityRulesTypes = Collections - .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); - + .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); for (String paramName : paramNames) { addRequirementToConnectResource(connectionPointEntry, supportedSecurityRulesTypes, paramName); } - } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List<String> supportedTypes) { - - + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, String nestedPropertyName, String connectionPointId, + Resource connectedResource, List<String> supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_SECURITY_RULE_PORT_CAPABILITY_CONNECTION, - nestedResourceId, nestedPropertyName, connectedResource.getType(), - connectionPointId, supportedTypes.toString()); - + logger.warn(LOG_UNSUPPORTED_SECURITY_RULE_PORT_CAPABILITY_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } - return true; } @Override Map.Entry<String, RequirementDefinition> createRequirementDefinition(String capabilityKey) { - - RequirementDefinition definition = new RequirementDefinition(); definition.setCapability(capabilityKey); definition.setRelationship(ToscaRelationshipType.ATTACHES_TO); @@ -157,6 +129,4 @@ class SecurityRulesToPortResourceConnection extends ResourceConnectionUsingCapab } }; } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java index 85a3f1df27..194d3fdb4f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java @@ -13,69 +13,51 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - public class UnifiedCompositionCatalogInstance implements UnifiedComposition { - - // There is consolidation in ScalingInstance implementation. - // In case of scaling instance, if there is more than one entry in the - // unifiedCompositionDataList, we should have consolidation between them. - // (all entries in the list are the once which need to be consolidated) - @Override - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - - UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); - - String substitutionNodeTypeId = - unifiedCompositionService.getSubstitutionNodeTypeId(serviceTemplate, - unifiedCompositionDataList.get(0), null, context); - // create one substitution ST for all computes - Optional<ServiceTemplate> substitutionServiceTemplate = - unifiedCompositionService.createUnifiedSubstitutionServiceTemplate(serviceTemplate, - unifiedCompositionDataList, context, substitutionNodeTypeId, null); - - if (!substitutionServiceTemplate.isPresent()) { - return; - } - - - // create abstract NT for each compute - for (int i = 0; i < unifiedCompositionDataList.size(); i++) { - List<UnifiedCompositionData> catalogInstanceUnifiedList = new ArrayList<>(); - catalogInstanceUnifiedList.add(unifiedCompositionDataList.get(i)); - - Integer index = unifiedCompositionDataList.size() > 1 ? i : null; - - String abstractSubstituteNodeTemplateId = unifiedCompositionService - .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), - catalogInstanceUnifiedList, substitutionNodeTypeId, context, index); - - unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, - serviceTemplate, catalogInstanceUnifiedList, context); - - unifiedCompositionService - .updateCompositionConnectivity(serviceTemplate, catalogInstanceUnifiedList, context); - - unifiedCompositionService - .cleanUnifiedCompositionEntities(serviceTemplate, catalogInstanceUnifiedList, context); + // There is consolidation in ScalingInstance implementation. + + // In case of scaling instance, if there is more than one entry in the + + // unifiedCompositionDataList, we should have consolidation between them. + + // (all entries in the list are the once which need to be consolidated) + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); + String substitutionNodeTypeId = unifiedCompositionService + .getSubstitutionNodeTypeId(serviceTemplate, unifiedCompositionDataList.get(0), null, context); + // create one substitution ST for all computes + Optional<ServiceTemplate> substitutionServiceTemplate = unifiedCompositionService + .createUnifiedSubstitutionServiceTemplate(serviceTemplate, unifiedCompositionDataList, context, substitutionNodeTypeId, null); + if (!substitutionServiceTemplate.isPresent()) { + return; + } + // create abstract NT for each compute + for (int i = 0; i < unifiedCompositionDataList.size(); i++) { + List<UnifiedCompositionData> catalogInstanceUnifiedList = new ArrayList<>(); + catalogInstanceUnifiedList.add(unifiedCompositionDataList.get(i)); + Integer index = unifiedCompositionDataList.size() > 1 ? i : null; + String abstractSubstituteNodeTemplateId = unifiedCompositionService + .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), catalogInstanceUnifiedList, + substitutionNodeTypeId, context, index); + unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, serviceTemplate, catalogInstanceUnifiedList, context); + unifiedCompositionService.updateCompositionConnectivity(serviceTemplate, catalogInstanceUnifiedList, context); + unifiedCompositionService.cleanUnifiedCompositionEntities(serviceTemplate, catalogInstanceUnifiedList, context); + } + unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); } - - unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); - unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java index 12d94720d6..e23ccfe6ee 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java @@ -19,6 +19,7 @@ */ package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; +import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; @@ -27,34 +28,30 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.compositi import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.util.List; - public class UnifiedCompositionNestedSingleCompute implements UnifiedComposition { + // There is no consolidation in NestedSingleCompute implementation. - // There is no consolidation in NestedSingleCompute implementation. - // In case of nested single compute, if there is more than one entry in the - // unifiedCompositionDataList, each one should be handed separately, no consolidation between - // them. - @Override - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { - return; - } + // In case of nested single compute, if there is more than one entry in the + + // unifiedCompositionDataList, each one should be handed separately, no consolidation between - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, nestedServiceTemplate, - unifiedCompositionDataList, context, null); - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - unifiedCompositionService.handleUnifiedNestedDefinition(unifiedCompositionTo, unifiedCompositionData); - String nestedNodeTemplateId = unifiedCompositionData.getNestedTemplateConsolidationData().getNodeTemplateId(); - unifiedCompositionService - .createNestedVfcInstanceGroup(nestedNodeTemplateId, unifiedCompositionTo, unifiedCompositionData); - unifiedCompositionService.updateUnifiedNestedConnectivity(unifiedCompositionTo, unifiedCompositionData); - unifiedCompositionService.cleanUnifiedNestedEntities(unifiedCompositionTo, unifiedCompositionData); - unifiedCompositionService.updateSubstitutionNodeTypePrefix(nestedServiceTemplate); + // them. + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { + return; + } + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, nestedServiceTemplate, unifiedCompositionDataList, + context, null); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + unifiedCompositionService.handleUnifiedNestedDefinition(unifiedCompositionTo, unifiedCompositionData); + String nestedNodeTemplateId = unifiedCompositionData.getNestedTemplateConsolidationData().getNodeTemplateId(); + unifiedCompositionService.createNestedVfcInstanceGroup(nestedNodeTemplateId, unifiedCompositionTo, unifiedCompositionData); + unifiedCompositionService.updateUnifiedNestedConnectivity(unifiedCompositionTo, unifiedCompositionData); + unifiedCompositionService.cleanUnifiedNestedEntities(unifiedCompositionTo, unifiedCompositionData); + unifiedCompositionService.updateSubstitutionNodeTypePrefix(nestedServiceTemplate); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java index 2d6360d5ab..759dc21414 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; +import java.util.List; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; @@ -23,51 +24,31 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.compositi import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.util.List; -import java.util.Optional; - public class UnifiedCompositionScalingInstances implements UnifiedComposition { - private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - - @Override - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - if (CollectionUtils.isEmpty(unifiedCompositionDataList) - || context.isUnifiedHandledServiceTemplate(serviceTemplate)) { - return; + private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + if (CollectionUtils.isEmpty(unifiedCompositionDataList) || context.isUnifiedHandledServiceTemplate(serviceTemplate)) { + return; + } + unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); + String substitutionNodeTypeId = unifiedCompositionService + .getSubstitutionNodeTypeId(serviceTemplate, unifiedCompositionDataList.get(0), null, context); + Optional<ServiceTemplate> substitutionServiceTemplate = unifiedCompositionService + .createUnifiedSubstitutionServiceTemplate(serviceTemplate, unifiedCompositionDataList, context, substitutionNodeTypeId, null); + if (!substitutionServiceTemplate.isPresent()) { + return; + } + String abstractSubstituteNodeTemplateId = unifiedCompositionService + .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), unifiedCompositionDataList, + substitutionNodeTypeId, context, null); + unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.updateCompositionConnectivity(serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.cleanUnifiedCompositionEntities(serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); } - - unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); - - String substitutionNodeTypeId = - unifiedCompositionService.getSubstitutionNodeTypeId(serviceTemplate, - unifiedCompositionDataList.get(0), null, context); - Optional<ServiceTemplate> substitutionServiceTemplate = - unifiedCompositionService.createUnifiedSubstitutionServiceTemplate(serviceTemplate, - unifiedCompositionDataList, context, substitutionNodeTypeId, null); - - if (!substitutionServiceTemplate.isPresent()) { - return; - } - - String abstractSubstituteNodeTemplateId = unifiedCompositionService - .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), - unifiedCompositionDataList, substitutionNodeTypeId, context, null); - - unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, - serviceTemplate, unifiedCompositionDataList, context); - - unifiedCompositionService - .updateCompositionConnectivity(serviceTemplate, unifiedCompositionDataList, context); - - unifiedCompositionService - .cleanUnifiedCompositionEntities(serviceTemplate, unifiedCompositionDataList, context); - - unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); - - unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java index 45326d0727..fda4cebc22 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; @@ -23,70 +25,49 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.compositi import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - - /** * The type Unified composition single substitution. */ public class UnifiedCompositionSingleSubstitution implements UnifiedComposition { - private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - - // There is no consolidation in SingleSubstitution implementation. - // In case of single substitution, if there is more than one entry in the - // unifiedCompositionDataList, they all should contain the same compute type but the - // consolidation between them was canceled. - // For different compute type, this implementation will be called more than once, each time - // per diff compute type, while sending one entry in the unifiedCompositionDataList. - @Override - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List<UnifiedCompositionData> unifiedCompositionDataList, - TranslationContext context) { - if (CollectionUtils.isEmpty(unifiedCompositionDataList) - || context.isUnifiedHandledServiceTemplate(serviceTemplate)) { - return; + private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + // There is no consolidation in SingleSubstitution implementation. + + // In case of single substitution, if there is more than one entry in the + + // unifiedCompositionDataList, they all should contain the same compute type but the + + // consolidation between them was canceled. + + // For different compute type, this implementation will be called more than once, each time + + // per diff compute type, while sending one entry in the unifiedCompositionDataList. + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List<UnifiedCompositionData> unifiedCompositionDataList, TranslationContext context) { + if (CollectionUtils.isEmpty(unifiedCompositionDataList) || context.isUnifiedHandledServiceTemplate(serviceTemplate)) { + return; + } + unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); + for (int i = 0; i < unifiedCompositionDataList.size(); i++) { + List<UnifiedCompositionData> singleSubstitutionUnifiedList = new ArrayList<>(); + singleSubstitutionUnifiedList.add(unifiedCompositionDataList.get(i)); + String substitutionNodeTypeId = unifiedCompositionService + .getSubstitutionNodeTypeId(serviceTemplate, singleSubstitutionUnifiedList.get(0), null, context); + Optional<ServiceTemplate> substitutionServiceTemplate = unifiedCompositionService + .createUnifiedSubstitutionServiceTemplate(serviceTemplate, singleSubstitutionUnifiedList, context, substitutionNodeTypeId, null); + if (!substitutionServiceTemplate.isPresent()) { + continue; + } + String abstractSubstituteNodeTemplateId = unifiedCompositionService + .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), singleSubstitutionUnifiedList, + substitutionNodeTypeId, context, null); + unifiedCompositionService + .createVfcInstanceGroup(abstractSubstituteNodeTemplateId, serviceTemplate, singleSubstitutionUnifiedList, context); + unifiedCompositionService.updateCompositionConnectivity(serviceTemplate, singleSubstitutionUnifiedList, context); + unifiedCompositionService.cleanUnifiedCompositionEntities(serviceTemplate, singleSubstitutionUnifiedList, context); + unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); + } + unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); } - - unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); - - for (int i = 0; i < unifiedCompositionDataList.size(); i++) { - List<UnifiedCompositionData> singleSubstitutionUnifiedList = new ArrayList<>(); - singleSubstitutionUnifiedList.add(unifiedCompositionDataList.get(i)); - - String substitutionNodeTypeId = - unifiedCompositionService.getSubstitutionNodeTypeId(serviceTemplate, - singleSubstitutionUnifiedList.get(0), null, context); - - Optional<ServiceTemplate> substitutionServiceTemplate = - unifiedCompositionService.createUnifiedSubstitutionServiceTemplate(serviceTemplate, - singleSubstitutionUnifiedList, context, substitutionNodeTypeId, null); - - if (!substitutionServiceTemplate.isPresent()) { - continue; - } - - String abstractSubstituteNodeTemplateId = unifiedCompositionService - .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), - singleSubstitutionUnifiedList, substitutionNodeTypeId, context, null); - - unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, - serviceTemplate, singleSubstitutionUnifiedList, context); - - unifiedCompositionService - .updateCompositionConnectivity(serviceTemplate, singleSubstitutionUnifiedList, context); - - unifiedCompositionService - .cleanUnifiedCompositionEntities(serviceTemplate, singleSubstitutionUnifiedList, context); - - unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); - } - - unifiedCompositionService - .cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); - - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java index 386b2e1ea9..64915a0af7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.mapping; import static org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator.getFunctionTranslateTo; @@ -52,321 +51,268 @@ import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslatio public class TranslatorHeatToToscaParameterConverter { - - private static Map<String, String> parameterTypeMapping; - private static Map<String, String> parameterEntrySchemaTypeMapping; - private static final String RANGE = "range"; - private static final String LENGTH = "length"; - private static final String MIN = "min"; - private static final String MAX = "max"; - private static final String ALLOWED_VALUES = "allowed_values"; - private static final String ALLOWED_PATTERN = "allowed_pattern"; - - - static { - parameterEntrySchemaTypeMapping = new HashMap<>(); - parameterEntrySchemaTypeMapping.put("list", "string"); - } - - static { - parameterTypeMapping = new HashMap<>(); - parameterTypeMapping.put("string", "string"); - parameterTypeMapping.put("number", "float"); - parameterTypeMapping.put("comma_delimited_list", "list"); - parameterTypeMapping.put("json", "json"); - parameterTypeMapping.put("boolean", "boolean"); - } - - /** - * Parameter converter map. - * - * @param parameters the parameters - * @param heatOrchestrationTemplate the heat orchestration template - * @param heatFileName the heat file name - * @param context the context - * @return the map - */ - public static Map<String, ParameterDefinition> parameterConverter(ServiceTemplate serviceTemplate, - Map<String, Parameter> parameters, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String heatFileName, String parentHeatFileName, - TranslationContext context, - Map<String, Object> heatEnvParameters) { - Map<String, ParameterDefinition> parameterDefinitionMap = new HashMap<>(); - for (Map.Entry<String, Parameter> entry : parameters.entrySet()) { - String heatParamName = entry.getKey(); - parameterDefinitionMap.put(heatParamName, - getToscaParameter(serviceTemplate,heatParamName, entry.getValue(), heatOrchestrationTemplate, heatFileName, - parentHeatFileName, context, heatEnvParameters)); + private static final String RANGE = "range"; + private static final String LENGTH = "length"; + private static final String MIN = "min"; + private static final String MAX = "max"; + private static final String ALLOWED_VALUES = "allowed_values"; + private static final String ALLOWED_PATTERN = "allowed_pattern"; + private static Map<String, String> parameterTypeMapping; + private static Map<String, String> parameterEntrySchemaTypeMapping; + + static { + parameterEntrySchemaTypeMapping = new HashMap<>(); + parameterEntrySchemaTypeMapping.put("list", "string"); } - return parameterDefinitionMap; - } - /** - * Parameter output converter map. - * - * @param parameters the parameters - * @param heatOrchestrationTemplate the heat orchestration template - * @param heatFileName the heat file name - * @param context the context - * @return the map - */ - public static Map<String, ParameterDefinition> parameterOutputConverter(ServiceTemplate serviceTemplate, - Map<String, Output> parameters, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String heatFileName, TranslationContext context) { - Map<String, ParameterDefinition> parameterDefinitionMap = new HashMap<>(); - for (Map.Entry<String, Output> entry : parameters.entrySet()) { - parameterDefinitionMap.put(entry.getKey(), - getToscaOutputParameter(serviceTemplate,entry.getKey(),entry.getValue(), - heatOrchestrationTemplate, - heatFileName, - context)); + static { + parameterTypeMapping = new HashMap<>(); + parameterTypeMapping.put("string", "string"); + parameterTypeMapping.put("number", "float"); + parameterTypeMapping.put("comma_delimited_list", "list"); + parameterTypeMapping.put("json", "json"); + parameterTypeMapping.put("boolean", "boolean"); } - return parameterDefinitionMap; - } - - /** - * Gets tosca parameter. - * - * @param heatParameter the heat parameter - * @param heatOrchestrationTemplate the heat orchestration template - * @param heatFileName the heat file name - * @param context the context - * @return the tosca parameter - */ - private static ParameterDefinitionExt getToscaParameter(ServiceTemplate serviceTemplate, - String heatParameterName, - Parameter heatParameter, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String heatFileName, - String parentHeatFileName, - TranslationContext context, - Map<String, Object> heatEnvParameters) { - - ParameterDefinitionExt toscaParameter = new ParameterDefinitionExt(); - toscaParameter.setType(getToscaParameterType(heatParameter.getType(), heatEnvParameters)); - toscaParameter.setEntry_schema(getToscaParameterEntrySchema(toscaParameter.getType())); - toscaParameter.setLabel(heatParameter.getLabel()); - toscaParameter.setDescription(heatParameter.getDescription()); - toscaParameter.set_default( - getToscaParameterDefaultValue(serviceTemplate, heatParameterName, heatParameter.get_default(), - toscaParameter.getType(), heatFileName, heatOrchestrationTemplate, context)); - toscaParameter.setHidden(heatParameter.isHidden()); - toscaParameter.setImmutable(heatParameter.isImmutable()); - toscaParameter.setConstraints(getToscaConstrains(heatParameter.getConstraints())); - Optional<Map<String, AnnotationDefinition>> annotations = getToscaAnnotations(context, heatFileName, parentHeatFileName, heatParameterName); - annotations.ifPresent(ant->toscaParameter.setAnnotations(annotations.get())); - - return toscaParameter; - } - - private static Optional<Map<String, AnnotationDefinition> > getToscaAnnotations (TranslationContext context, String heatFileName, String parentHeatFileName, String heatParameterName){ - - if(parentHeatFileName != null){ - heatFileName = parentHeatFileName; + /** + * Parameter converter map. + * + * @param parameters the parameters + * @param heatOrchestrationTemplate the heat orchestration template + * @param heatFileName the heat file name + * @param context the context + * @return the map + */ + public static Map<String, ParameterDefinition> parameterConverter(ServiceTemplate serviceTemplate, Map<String, Parameter> parameters, + HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, + String parentHeatFileName, TranslationContext context, + Map<String, Object> heatEnvParameters) { + Map<String, ParameterDefinition> parameterDefinitionMap = new HashMap<>(); + for (Map.Entry<String, Parameter> entry : parameters.entrySet()) { + String heatParamName = entry.getKey(); + parameterDefinitionMap.put(heatParamName, + getToscaParameter(serviceTemplate, heatParamName, entry.getValue(), heatOrchestrationTemplate, heatFileName, parentHeatFileName, + context, heatEnvParameters)); + } + return parameterDefinitionMap; } - if(!isAnnotationRequired(context, heatFileName)){ - return Optional.empty(); + /** + * Parameter output converter map. + * + * @param parameters the parameters + * @param heatOrchestrationTemplate the heat orchestration template + * @param heatFileName the heat file name + * @param context the context + * @return the map + */ + public static Map<String, ParameterDefinition> parameterOutputConverter(ServiceTemplate serviceTemplate, Map<String, Output> parameters, + HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, + TranslationContext context) { + Map<String, ParameterDefinition> parameterDefinitionMap = new HashMap<>(); + for (Map.Entry<String, Output> entry : parameters.entrySet()) { + parameterDefinitionMap.put(entry.getKey(), + getToscaOutputParameter(serviceTemplate, entry.getKey(), entry.getValue(), heatOrchestrationTemplate, heatFileName, context)); + } + return parameterDefinitionMap; } - AnnotationDefinition annotationDefinition = new AnnotationDefinition(); - annotationDefinition.setType(ToscaAnnotationType.SOURCE); - annotationDefinition.setProperties(new HashMap<>()); - List<String> vfModuleList = new ArrayList<>(); - vfModuleList.add( FileUtils.getFileWithoutExtention(heatFileName)); - annotationDefinition.getProperties().put(ToscaConstants.VF_MODULE_LABEL_PROPERTY_NAME, vfModuleList); - annotationDefinition.getProperties().put(ToscaConstants.SOURCE_TYPE_PROPERTY_NAME, ToscaConstants.HEAT_SOURCE_TYPE); - annotationDefinition.getProperties().put(ToscaConstants.PARAM_NAME_PROPERTY_NAME, heatParameterName); - Map<String, AnnotationDefinition> annotationMap = new HashMap<>(); - annotationMap.put(ToscaConstants.SOURCE_ANNOTATION_ID, annotationDefinition); - return Optional.of(annotationMap); - - } - - private static boolean isAnnotationRequired(TranslationContext context, String heatFileName){ - return !isNestedServiceTemplate(context, heatFileName); - } - - private static boolean isNestedServiceTemplate(TranslationContext context, String heatFileName) { - return HeatToToscaUtil.isHeatFileNested(context, heatFileName); - } - - - /** - * Gets tosca output parameter. - * - * @param heatOutputParameter the heat output parameter - * @param heatOrchestrationTemplate the heat orchestration template - * @param heatFileName the heat file name - * @param context the context - * @return the tosca output parameter - */ - private static ParameterDefinitionExt getToscaOutputParameter(ServiceTemplate serviceTemplate, - String parameterName, - Output heatOutputParameter, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - String heatFileName, - TranslationContext context) { - - ParameterDefinitionExt toscaParameter = new ParameterDefinitionExt(); - toscaParameter.setDescription(heatOutputParameter.getDescription()); - toscaParameter.setValue( - getToscaParameterDefaultValue(serviceTemplate,parameterName,heatOutputParameter.getValue(), - toscaParameter.getType(), - heatFileName, heatOrchestrationTemplate, context)); - return toscaParameter; - } - - /** - * Gets tosca parameter default value. - * - * @param obj the a default - * @param type the type - * @param heatFileName the heat file name - * @param heatOrchestrationTemplate the heat orchestration template - * @param context the context - * @return the tosca parameter default value - */ - public static Object getToscaParameterDefaultValue(ServiceTemplate serviceTemplate, - String parameterName, - Object obj, String type, - String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - TranslationContext context) { - - if (obj == null) { - return null; - } - Object toscaDefaultValue = obj; - if ("list".equals(type)) { - if (obj instanceof String) { - return Arrays.asList(((String) obj).split(",")); - } else { - return toscaDefaultValue; - } + /** + * Gets tosca parameter. + * + * @param heatParameter the heat parameter + * @param heatOrchestrationTemplate the heat orchestration template + * @param heatFileName the heat file name + * @param context the context + * @return the tosca parameter + */ + private static ParameterDefinitionExt getToscaParameter(ServiceTemplate serviceTemplate, String heatParameterName, Parameter heatParameter, + HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, + String parentHeatFileName, TranslationContext context, + Map<String, Object> heatEnvParameters) { + ParameterDefinitionExt toscaParameter = new ParameterDefinitionExt(); + toscaParameter.setType(getToscaParameterType(heatParameter.getType(), heatEnvParameters)); + toscaParameter.setEntry_schema(getToscaParameterEntrySchema(toscaParameter.getType())); + toscaParameter.setLabel(heatParameter.getLabel()); + toscaParameter.setDescription(heatParameter.getDescription()); + toscaParameter.set_default( + getToscaParameterDefaultValue(serviceTemplate, heatParameterName, heatParameter.get_default(), toscaParameter.getType(), heatFileName, + heatOrchestrationTemplate, context)); + toscaParameter.setHidden(heatParameter.isHidden()); + toscaParameter.setImmutable(heatParameter.isImmutable()); + toscaParameter.setConstraints(getToscaConstrains(heatParameter.getConstraints())); + Optional<Map<String, AnnotationDefinition>> annotations = getToscaAnnotations(context, heatFileName, parentHeatFileName, heatParameterName); + annotations.ifPresent(ant -> toscaParameter.setAnnotations(annotations.get())); + return toscaParameter; } - return getToscaParameterValue(serviceTemplate,parameterName,toscaDefaultValue, heatFileName, - heatOrchestrationTemplate, - context); - } - - private static Object getToscaParameterValue(ServiceTemplate serviceTemplate, - String parameterName, - Object paramValue, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - if (paramValue instanceof Map) { - if(MapUtils.isEmpty((Map) paramValue)){ - return new HashMap<>(); - } - Map.Entry<String, Object> functionMapEntry = - (Map.Entry<String, Object>) ((Map) paramValue).entrySet().iterator().next(); - if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { - - FunctionTranslator functionTranslator = new FunctionTranslator(getFunctionTranslateTo(serviceTemplate, null, - heatFileName, heatOrchestrationTemplate, context), parameterName, functionMapEntry.getValue(), null); - return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get() - .translateFunction(functionTranslator); - } + private static Optional<Map<String, AnnotationDefinition>> getToscaAnnotations(TranslationContext context, String heatFileName, + String parentHeatFileName, String heatParameterName) { + if (parentHeatFileName != null) { + heatFileName = parentHeatFileName; + } + if (!isAnnotationRequired(context, heatFileName)) { + return Optional.empty(); + } + AnnotationDefinition annotationDefinition = new AnnotationDefinition(); + annotationDefinition.setType(ToscaAnnotationType.SOURCE); + annotationDefinition.setProperties(new HashMap<>()); + List<String> vfModuleList = new ArrayList<>(); + vfModuleList.add(FileUtils.getFileWithoutExtention(heatFileName)); + annotationDefinition.getProperties().put(ToscaConstants.VF_MODULE_LABEL_PROPERTY_NAME, vfModuleList); + annotationDefinition.getProperties().put(ToscaConstants.SOURCE_TYPE_PROPERTY_NAME, ToscaConstants.HEAT_SOURCE_TYPE); + annotationDefinition.getProperties().put(ToscaConstants.PARAM_NAME_PROPERTY_NAME, heatParameterName); + Map<String, AnnotationDefinition> annotationMap = new HashMap<>(); + annotationMap.put(ToscaConstants.SOURCE_ANNOTATION_ID, annotationDefinition); + return Optional.of(annotationMap); } - return paramValue; - } - - private static List<Constraint> getToscaConstrains(List<Map<String, Object>> constraints) { - if (constraints == null) { - return null; + private static boolean isAnnotationRequired(TranslationContext context, String heatFileName) { + return !isNestedServiceTemplate(context, heatFileName); } - List<Constraint> constraintList = new ArrayList<>(); - - for (Map<String, Object> constraint : constraints) { - constraintList.addAll(getToscaParameterConstraint(constraint)); + private static boolean isNestedServiceTemplate(TranslationContext context, String heatFileName) { + return HeatToToscaUtil.isHeatFileNested(context, heatFileName); } - return constraintList; - } - - private static List<Constraint> getToscaParameterConstraint(Map<String, Object> constraint) { - List<Constraint> convertedConstraintList = new ArrayList<>(); - Constraint convertedConstraint; - - if (constraint.containsKey(RANGE)) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - Integer min = (Integer) ((Map) constraint.get(RANGE)).get(MIN); - Integer max = (Integer) ((Map) constraint.get(RANGE)).get(MAX); - convertedConstraint.setIn_range(new Integer[]{min, max}); - - } else if (constraint.containsKey(LENGTH)) { - Integer min = (Integer) ((Map) constraint.get(LENGTH)).get(MIN); - Integer max = (Integer) ((Map) constraint.get(LENGTH)).get(MAX); - if (max != null) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - convertedConstraint.setMax_length(max); - } - if (min != null) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - convertedConstraint.setMin_length(min); - } - } else if (constraint.containsKey(ALLOWED_VALUES)) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - convertedConstraint.setValid_values((List) constraint.get(ALLOWED_VALUES)); - } else if (constraint.containsKey(ALLOWED_PATTERN)) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - convertedConstraint.setPattern(constraint.get(ALLOWED_PATTERN)); + /** + * Gets tosca output parameter. + * + * @param heatOutputParameter the heat output parameter + * @param heatOrchestrationTemplate the heat orchestration template + * @param heatFileName the heat file name + * @param context the context + * @return the tosca output parameter + */ + private static ParameterDefinitionExt getToscaOutputParameter(ServiceTemplate serviceTemplate, String parameterName, Output heatOutputParameter, + HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, + TranslationContext context) { + ParameterDefinitionExt toscaParameter = new ParameterDefinitionExt(); + toscaParameter.setDescription(heatOutputParameter.getDescription()); + toscaParameter.setValue( + getToscaParameterDefaultValue(serviceTemplate, parameterName, heatOutputParameter.getValue(), toscaParameter.getType(), heatFileName, + heatOrchestrationTemplate, context)); + return toscaParameter; } - return convertedConstraintList; - } - - private static EntrySchema getToscaParameterEntrySchema(String type) { + /** + * Gets tosca parameter default value. + * + * @param obj the a default + * @param type the type + * @param heatFileName the heat file name + * @param heatOrchestrationTemplate the heat orchestration template + * @param context the context + * @return the tosca parameter default value + */ + public static Object getToscaParameterDefaultValue(ServiceTemplate serviceTemplate, String parameterName, Object obj, String type, + String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context) { + if (obj == null) { + return null; + } + Object toscaDefaultValue = obj; + if ("list".equals(type)) { + if (obj instanceof String) { + return Arrays.asList(((String) obj).split(",")); + } else { + return toscaDefaultValue; + } + } + return getToscaParameterValue(serviceTemplate, parameterName, toscaDefaultValue, heatFileName, heatOrchestrationTemplate, context); + } - if (!parameterEntrySchemaTypeMapping.containsKey(type)) { - return null; + private static Object getToscaParameterValue(ServiceTemplate serviceTemplate, String parameterName, Object paramValue, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { + if (paramValue instanceof Map) { + if (MapUtils.isEmpty((Map) paramValue)) { + return new HashMap<>(); + } + Map.Entry<String, Object> functionMapEntry = (Map.Entry<String, Object>) ((Map) paramValue).entrySet().iterator().next(); + if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { + FunctionTranslator functionTranslator = new FunctionTranslator( + getFunctionTranslateTo(serviceTemplate, null, heatFileName, heatOrchestrationTemplate, context), parameterName, + functionMapEntry.getValue(), null); + return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get().translateFunction(functionTranslator); + } + } + return paramValue; } - EntrySchema entrySchema = new EntrySchema(); - entrySchema.setType(parameterEntrySchemaTypeMapping.get(type)); - return entrySchema; - } + private static List<Constraint> getToscaConstrains(List<Map<String, Object>> constraints) { + if (constraints == null) { + return null; + } + List<Constraint> constraintList = new ArrayList<>(); + for (Map<String, Object> constraint : constraints) { + constraintList.addAll(getToscaParameterConstraint(constraint)); + } + return constraintList; + } - protected static String getToscaParameterType(final String heatParameterType, - final Map<String, Object> heatEnvParameters) { - if (heatEnvParameters != null && DefinedHeatParameterTypes.NUMBER.getType().equals(heatParameterType)) { - if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitSize.class) != null) { - return ToscaScalarUnitTypes.SCALAR_UNIT_SIZE.getType(); - } else if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitTime.class) != null) { - return ToscaScalarUnitTypes.SCALAR_UNIT_TIME.getType(); - } else if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitFrequency.class) != null) { - return ToscaScalarUnitTypes.SCALAR_UNIT_FREQUENCY.getType(); - } + private static List<Constraint> getToscaParameterConstraint(Map<String, Object> constraint) { + List<Constraint> convertedConstraintList = new ArrayList<>(); + Constraint convertedConstraint; + if (constraint.containsKey(RANGE)) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + Integer min = (Integer) ((Map) constraint.get(RANGE)).get(MIN); + Integer max = (Integer) ((Map) constraint.get(RANGE)).get(MAX); + convertedConstraint.setIn_range(new Integer[]{min, max}); + } else if (constraint.containsKey(LENGTH)) { + Integer min = (Integer) ((Map) constraint.get(LENGTH)).get(MIN); + Integer max = (Integer) ((Map) constraint.get(LENGTH)).get(MAX); + if (max != null) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + convertedConstraint.setMax_length(max); + } + if (min != null) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + convertedConstraint.setMin_length(min); + } + } else if (constraint.containsKey(ALLOWED_VALUES)) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + convertedConstraint.setValid_values((List) constraint.get(ALLOWED_VALUES)); + } else if (constraint.containsKey(ALLOWED_PATTERN)) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + convertedConstraint.setPattern(constraint.get(ALLOWED_PATTERN)); + } + return convertedConstraintList; } - return parameterTypeMapping.get(heatParameterType); - } + private static EntrySchema getToscaParameterEntrySchema(String type) { + if (!parameterEntrySchemaTypeMapping.containsKey(type)) { + return null; + } + EntrySchema entrySchema = new EntrySchema(); + entrySchema.setType(parameterEntrySchemaTypeMapping.get(type)); + return entrySchema; + } - private static <E extends Enum<E>> String getScalarUnitType(final Map<String, Object> heatEnvParameters, - final Class<E> enumClass) { - final ScalarUnitValidator scalarUnitValidator = ScalarUnitValidator.getInstance(); - if (Arrays.stream(enumClass.getEnumConstants()).anyMatch(unitType -> - heatEnvParameters.values().stream().filter(Objects::nonNull) - .anyMatch(parameterValue -> scalarUnitValidator.isScalarUnit(parameterValue.toString()) && - Arrays.stream(StringUtils.split(parameterValue.toString())) - .anyMatch(strParamValue -> strParamValue.equalsIgnoreCase(unitType.name()))))) { - return enumClass.getTypeName(); + protected static String getToscaParameterType(final String heatParameterType, final Map<String, Object> heatEnvParameters) { + if (heatEnvParameters != null && DefinedHeatParameterTypes.NUMBER.getType().equals(heatParameterType)) { + if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitSize.class) != null) { + return ToscaScalarUnitTypes.SCALAR_UNIT_SIZE.getType(); + } else if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitTime.class) != null) { + return ToscaScalarUnitTypes.SCALAR_UNIT_TIME.getType(); + } else if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitFrequency.class) != null) { + return ToscaScalarUnitTypes.SCALAR_UNIT_FREQUENCY.getType(); + } + } + return parameterTypeMapping.get(heatParameterType); } - return null; - } + private static <E extends Enum<E>> String getScalarUnitType(final Map<String, Object> heatEnvParameters, final Class<E> enumClass) { + final ScalarUnitValidator scalarUnitValidator = ScalarUnitValidator.getInstance(); + if (Arrays.stream(enumClass.getEnumConstants()).anyMatch(unitType -> heatEnvParameters.values().stream().filter(Objects::nonNull).anyMatch( + parameterValue -> scalarUnitValidator.isScalarUnit(parameterValue.toString()) && Arrays + .stream(StringUtils.split(parameterValue.toString())).anyMatch(strParamValue -> strParamValue.equalsIgnoreCase(unitType.name()))))) { + return enumClass.getTypeName(); + } + return null; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java index 967f1f92ce..b9cad2f474 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.mapping; +import static org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator.getFunctionTranslateTo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.onap.sdc.tosca.datatypes.model.Template; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; @@ -29,138 +34,110 @@ import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator.getFunctionTranslateTo; - public class TranslatorHeatToToscaPropertyConverter { - /** - * Gets tosca properties simple conversion. - * - * @param heatProperties the heat properties - * @param toscaProperties the tosca properties - * @param heatFileName the heat file name - * @param heatOrchestrationTemplate the heat orchestration template - * @param resourceType the resource type - * @param template the template - * @param context the context - * @return the tosca properties simple conversion - */ - //Convert property assuming the property type in heat is same as the property type in tosca - public static Map<String, Object> getToscaPropertiesSimpleConversion(ServiceTemplate - serviceTemplate, - String resourceId,Map<String, Object> heatProperties, Map<String, Object> toscaProperties, - String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, String - resourceType, Template template, TranslationContext context) { - - toscaProperties = toscaProperties != null ? toscaProperties : new HashMap<>(); + /** + * Gets tosca properties simple conversion. + * + * @param heatProperties the heat properties + * @param toscaProperties the tosca properties + * @param heatFileName the heat file name + * @param heatOrchestrationTemplate the heat orchestration template + * @param resourceType the resource type + * @param template the template + * @param context the context + * @return the tosca properties simple conversion + */ - for (String heatPropertyName : context.getElementSet(resourceType, Constants.PROP)) { - - setSimpleProperty(serviceTemplate, resourceId, heatProperties, heatFileName, resourceType, - heatOrchestrationTemplate, - context, toscaProperties, heatPropertyName, null, template); + //Convert property assuming the property type in heat is same as the property type in tosca + public static Map<String, Object> getToscaPropertiesSimpleConversion(ServiceTemplate serviceTemplate, String resourceId, + Map<String, Object> heatProperties, Map<String, Object> toscaProperties, + String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceType, Template template, TranslationContext context) { + toscaProperties = toscaProperties != null ? toscaProperties : new HashMap<>(); + for (String heatPropertyName : context.getElementSet(resourceType, Constants.PROP)) { + setSimpleProperty(serviceTemplate, resourceId, heatProperties, heatFileName, resourceType, heatOrchestrationTemplate, context, + toscaProperties, heatPropertyName, null, template); + } + return toscaProperties; } - return toscaProperties; - } - /** - * Sets simple property. - * - * @param heatProperties the heat properties - * @param heatFileName the heat file name - * @param resourceType the resource type - * @param heatOrchestrationTemplate the heat orchestration template - * @param context the context - * @param toscaProperties the tosca properties - * @param heatPropertyName the heat property name - * @param toscaPropertyName the tosca property name - * @param template the template - */ - public static void setSimpleProperty(ServiceTemplate serviceTemplate,String resourceId, - Map<String, Object> heatProperties, - String heatFileName, - String resourceType, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context, - Map<String, Object> toscaProperties, String heatPropertyName, - String toscaPropertyName, Template template) { - Object propertyValue = null; - if (heatProperties != null) { - propertyValue = heatProperties.get(heatPropertyName); - } - if (propertyValue == null) { - return; + /** + * Sets simple property. + * + * @param heatProperties the heat properties + * @param heatFileName the heat file name + * @param resourceType the resource type + * @param heatOrchestrationTemplate the heat orchestration template + * @param context the context + * @param toscaProperties the tosca properties + * @param heatPropertyName the heat property name + * @param toscaPropertyName the tosca property name + * @param template the template + */ + public static void setSimpleProperty(ServiceTemplate serviceTemplate, String resourceId, Map<String, Object> heatProperties, String heatFileName, + String resourceType, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context, + Map<String, Object> toscaProperties, String heatPropertyName, String toscaPropertyName, Template template) { + Object propertyValue = null; + if (heatProperties != null) { + propertyValue = heatProperties.get(heatPropertyName); + } + if (propertyValue == null) { + return; + } + if (toscaPropertyName == null) { + toscaPropertyName = resourceType == null ? heatPropertyName : context.getElementMapping(resourceType, Constants.PROP, heatPropertyName); + if (toscaPropertyName == null) { + return; + } + } + toscaProperties.put(toscaPropertyName, + getToscaPropertyValue(serviceTemplate, resourceId, heatPropertyName, propertyValue, resourceType, heatFileName, heatOrchestrationTemplate, + template, context)); } - if (toscaPropertyName == null) { - toscaPropertyName = resourceType == null ? heatPropertyName - : context.getElementMapping(resourceType, Constants.PROP, heatPropertyName); - if (toscaPropertyName == null) { - return; - } - } - toscaProperties.put(toscaPropertyName, - getToscaPropertyValue(serviceTemplate, resourceId,heatPropertyName, propertyValue, - resourceType, - heatFileName, heatOrchestrationTemplate, template, context)); - } - - - /** - * Gets tosca property value. - * - * @param propertyName the property name - * @param propertyValue the property value - * @param resourceType the resource type - * @param heatFileName the heat file name - * @param heatOrchestrationTemplate the heat orchestration template - * @param template the template - * @param context the context - * @return the tosca property value - */ - public static Object getToscaPropertyValue(ServiceTemplate serviceTemplate, String resourceId, - String propertyName, Object propertyValue, - String resourceType, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Template template, TranslationContext context) { - if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { - Map.Entry<String, Object> functionMapEntry = - (Map.Entry<String, Object>) ((Map) propertyValue).entrySet().iterator().next(); - if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { - FunctionTranslator functionTranslator = new FunctionTranslator(getFunctionTranslateTo(serviceTemplate, - resourceId, heatFileName, heatOrchestrationTemplate, context), propertyName, - functionMapEntry.getValue(), template); - return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get() - .translateFunction(functionTranslator); - } - Map<String, Object> propertyValueMap = new HashMap<>(); - for (Map.Entry<String, Object> entry : ((Map<String, Object>) propertyValue).entrySet()) { - String toscaPropertyName = resourceType == null ? null : context - .getElementMapping(resourceType, Constants.PROP, propertyName - + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR + entry.getKey()); - toscaPropertyName = toscaPropertyName != null ? toscaPropertyName : entry.getKey(); - propertyValueMap.put(toscaPropertyName, - getToscaPropertyValue(serviceTemplate, resourceId, - propertyName + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR - + entry.getKey(), entry.getValue(), resourceType, heatFileName, - heatOrchestrationTemplate, template, context)); - } - return propertyValueMap; - } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { - List propertyValueArray = new ArrayList<>(); - for (int i = 0; i < ((List) propertyValue).size(); i++) { - propertyValueArray.add( - getToscaPropertyValue(serviceTemplate, resourceId, propertyName, ((List) - propertyValue).get(i), - resourceType, heatFileName, heatOrchestrationTemplate, template, context)); - } - return propertyValueArray; + /** + * Gets tosca property value. + * + * @param propertyName the property name + * @param propertyValue the property value + * @param resourceType the resource type + * @param heatFileName the heat file name + * @param heatOrchestrationTemplate the heat orchestration template + * @param template the template + * @param context the context + * @return the tosca property value + */ + public static Object getToscaPropertyValue(ServiceTemplate serviceTemplate, String resourceId, String propertyName, Object propertyValue, + String resourceType, String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + Template template, TranslationContext context) { + if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { + Map.Entry<String, Object> functionMapEntry = (Map.Entry<String, Object>) ((Map) propertyValue).entrySet().iterator().next(); + if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { + FunctionTranslator functionTranslator = new FunctionTranslator( + getFunctionTranslateTo(serviceTemplate, resourceId, heatFileName, heatOrchestrationTemplate, context), propertyName, + functionMapEntry.getValue(), template); + return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get().translateFunction(functionTranslator); + } + Map<String, Object> propertyValueMap = new HashMap<>(); + for (Map.Entry<String, Object> entry : ((Map<String, Object>) propertyValue).entrySet()) { + String toscaPropertyName = resourceType == null ? null : context + .getElementMapping(resourceType, Constants.PROP, propertyName + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR + entry.getKey()); + toscaPropertyName = toscaPropertyName != null ? toscaPropertyName : entry.getKey(); + propertyValueMap.put(toscaPropertyName, + getToscaPropertyValue(serviceTemplate, resourceId, propertyName + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR + entry.getKey(), + entry.getValue(), resourceType, heatFileName, heatOrchestrationTemplate, template, context)); + } + return propertyValueMap; + } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { + List propertyValueArray = new ArrayList<>(); + for (int i = 0; i < ((List) propertyValue).size(); i++) { + propertyValueArray.add( + getToscaPropertyValue(serviceTemplate, resourceId, propertyName, ((List) propertyValue).get(i), resourceType, heatFileName, + heatOrchestrationTemplate, template, context)); + } + return propertyValueArray; + } + return propertyValue; } - return propertyValue; - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java index c3c1febf40..50738e9404 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.utils; import java.io.BufferedReader; @@ -33,7 +32,6 @@ import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; - import org.apache.commons.io.IOUtils; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -41,119 +39,103 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class ResourceWalker { - private static final String RESOURCE_FILE_READ_ERROR = "Can't read resource file from class path."; - - private ResourceWalker() { - } - - /** - * Read resources from directory map. - * - * @param resourceDirectoryToStart the resource directory to start - * @return the map of file where key is file name and value is its data - * @throws Exception the exception - */ - public static Map<String, String> readResourcesFromDirectory(String resourceDirectoryToStart) - throws - Exception { - Map<String, String> filesContent = new HashMap<>(); - traverse(resourceDirectoryToStart, (fileName, stream) -> { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { - filesContent.put(fileName, IOUtils.toString(reader)); - } catch (IOException exception) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(RESOURCE_FILE_READ_ERROR - + " File name = " + fileName) - .withId("Resource Read Error").withCategory(ErrorCategory.APPLICATION).build(), - exception); - } - }); - return filesContent; - } + private static final String RESOURCE_FILE_READ_ERROR = "Can't read resource file from class path."; - private static void traverse(String start, BiConsumer<String, InputStream> handler) throws - Exception { - - URL url = ResourceWalker.class.getClassLoader().getResource(start); - if (url == null) { - throw new FileNotFoundException("Resource not found: " + start); + private ResourceWalker() { } - switch (url.getProtocol().toLowerCase()) { + /** + * Read resources from directory map. + * + * @param resourceDirectoryToStart the resource directory to start + * @return the map of file where key is file name and value is its data + * @throws Exception the exception + */ + public static Map<String, String> readResourcesFromDirectory(String resourceDirectoryToStart) throws Exception { + Map<String, String> filesContent = new HashMap<>(); + traverse(resourceDirectoryToStart, (fileName, stream) -> { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { + filesContent.put(fileName, IOUtils.toString(reader)); + } catch (IOException exception) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(RESOURCE_FILE_READ_ERROR + " File name = " + fileName) + .withId("Resource Read Error").withCategory(ErrorCategory.APPLICATION).build(), exception); + } + }); + return filesContent; + } - case "file": - traverseFile(new File(url.getPath()), handler); - break; - case "zip": - case "jar": - String path = url.getPath(); - int resourcePosition = path.lastIndexOf("!/" + start); - traverseArchive(path.substring(0, resourcePosition), start, handler); - break; - default: - throw new IllegalArgumentException("Unknown protocol"); + private static void traverse(String start, BiConsumer<String, InputStream> handler) throws Exception { + URL url = ResourceWalker.class.getClassLoader().getResource(start); + if (url == null) { + throw new FileNotFoundException("Resource not found: " + start); + } + switch (url.getProtocol().toLowerCase()) { + case "file": + traverseFile(new File(url.getPath()), handler); + break; + case "zip": + case "jar": + String path = url.getPath(); + int resourcePosition = path.lastIndexOf("!/" + start); + traverseArchive(path.substring(0, resourcePosition), start, handler); + break; + default: + throw new IllegalArgumentException("Unknown protocol"); + } } - } - private static void traverseArchive(String file, String resource, BiConsumer<String, InputStream> - handler) - throws URISyntaxException, IOException { + private static void traverseArchive(String file, String resource, BiConsumer<String, InputStream> handler) + throws URISyntaxException, IOException { + // There is what looks like a bug in Java: - // There is what looks like a bug in Java: - // if "abc" is a directory in an archive, - // both "abc" and "abc/" will be found successfully. - // However, calling isDirectory() will return "true" for "abc/", - // but "false" for "abc". - try (ZipFile zip = new ZipFile(new URI(file).getPath())) { + // if "abc" is a directory in an archive, - Predicate<ZipEntry> predicate = buildPredicate(resource); - Enumeration<? extends ZipEntry> entries = zip.entries(); - while (entries.hasMoreElements()) { - handleZipEntry(predicate, zip, entries.nextElement(), handler); - } - } - } + // both "abc" and "abc/" will be found successfully. - private static Predicate<ZipEntry> buildPredicate(String resource) { + // However, calling isDirectory() will return "true" for "abc/", - if (resource.endsWith("/")) { - return zipEntry -> - zipEntry.getName().startsWith(resource) && !zipEntry.isDirectory(); - } else { - return zipEntry -> { - String name = zipEntry.getName(); - return (name.equals(resource) || name.startsWith(resource + "/")) - && !zipEntry.isDirectory() && !name.contains("../"); - }; + // but "false" for "abc". + try (ZipFile zip = new ZipFile(new URI(file).getPath())) { + Predicate<ZipEntry> predicate = buildPredicate(resource); + Enumeration<? extends ZipEntry> entries = zip.entries(); + while (entries.hasMoreElements()) { + handleZipEntry(predicate, zip, entries.nextElement(), handler); + } + } } - } - - private static void handleZipEntry(Predicate<ZipEntry> predicate, ZipFile zip, ZipEntry zipEntry, - BiConsumer<String, InputStream> handler) - throws IOException { - - if (predicate.test(zipEntry)) { - try (InputStream input = zip.getInputStream(zipEntry)) { - handler.accept(zipEntry.getName(), input); - } + private static Predicate<ZipEntry> buildPredicate(String resource) { + if (resource.endsWith("/")) { + return zipEntry -> zipEntry.getName().startsWith(resource) && !zipEntry.isDirectory(); + } else { + return zipEntry -> { + String name = zipEntry.getName(); + return (name.equals(resource) || name.startsWith(resource + "/")) && !zipEntry.isDirectory() && !name.contains("../"); + }; + } } - } - private static void traverseFile(File file, BiConsumer<String, InputStream> handler) throws - IOException { + private static void handleZipEntry(Predicate<ZipEntry> predicate, ZipFile zip, ZipEntry zipEntry, BiConsumer<String, InputStream> handler) + throws IOException { + if (predicate.test(zipEntry)) { + try (InputStream input = zip.getInputStream(zipEntry)) { + handler.accept(zipEntry.getName(), input); + } + } + } - if (file.isDirectory()) { - File[] files = file.listFiles(); - if (files != null) { - for (File sub : files) { - traverseFile(sub, handler); + private static void traverseFile(File file, BiConsumer<String, InputStream> handler) throws IOException { + if (file.isDirectory()) { + File[] files = file.listFiles(); + if (files != null) { + for (File sub : files) { + traverseFile(sub, handler); + } + } + } else { + try (FileInputStream stream = new FileInputStream(file)) { + handler.accept(file.getPath(), stream); + } } - } - } else { - try (FileInputStream stream = new FileInputStream(file)) { - handler.accept(file.getPath(), stream); - } } - } } |