From 1ec3dde2067e0181faa8e5098219c93126638aef Mon Sep 17 00:00:00 2001 From: vasraz Date: Mon, 6 Jul 2020 17:08:08 +0100 Subject: Support for defining attributes on a node_type This commit aims to add support of attributes on node_type. It is first of several commits to cover all support. It includes: - new classes: AttributeDefinition ComponentInstanceAttribute IAttributeInputCommon IAttributeInputCommon AttributeDataDefinition MapAttributesDataDefinition - support of 'Import of VFC with attributes' - TCs fix for changed code Next commit(s) will cover: - support of "Onboarding packages with attributes" - support of "Download TOSCA Artifacts - Tosca Model" - support of "Import onboarded VSP" Change-Id: I0167abc58e8aeef3d631833cc323e466f8e71492 Signed-off-by: Vasyl Razinkov Issue-ID: SDC-3200 --- .../be/components/impl/AttributeBusinessLogic.java | 47 +- .../be/components/impl/ComponentBusinessLogic.java | 19 +- .../impl/ComponentInstanceBusinessLogic.java | 32 +- .../sdc/be/components/impl/ImportUtils.java | 98 ++-- .../be/components/impl/ResourceBusinessLogic.java | 123 ++--- .../be/components/impl/ResourceImportManager.java | 535 +++++++++++++-------- .../sdc/be/servlets/AttributeServlet.java | 30 +- .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 9 + .../sdc/be/tosca/model/ToscaNodeTemplate.java | 9 +- .../sdc/be/tosca/model/ToscaNodeType.java | 70 +-- .../impl/AttributeBusinessLogicTest.java | 165 +++---- .../impl/ComponentInstanceBusinessLogicTest.java | 34 +- .../sdc/be/components/impl/ImportUtilsTest.java | 18 +- 13 files changed, 631 insertions(+), 558 deletions(-) (limited to 'catalog-be') diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java index c0f08b0bb3..ef82eba0a4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java @@ -23,9 +23,10 @@ package org.openecomp.sdc.be.components.impl; import fj.data.Either; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.DataTypeDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; @@ -59,7 +60,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { private static final String UPDATE_ATTRIBUTE = "UpdateAttribute"; private static final String DELETE_ATTRIBUTE = "DeleteAttribute"; - private static final Logger log = Logger.getLogger(AttributeBusinessLogic.class.getName()); + private static final Logger log = Logger.getLogger(AttributeBusinessLogic.class); private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {}. Error - {}"; @Autowired @@ -82,8 +83,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return AttributeDefinition if created successfully Or ResponseFormat */ - public Either createAttribute(String resourceId, PropertyDefinition newAttributeDef, String userId) { - Either result = null; + public Either createAttribute(String resourceId, AttributeDataDefinition newAttributeDef, String userId) { + Either result = null; validateUserExists(userId); StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); @@ -112,17 +113,17 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } Map eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); // validate property default values - Either defaultValuesValidation = validatePropertyDefaultValue(newAttributeDef, eitherAllDataTypes); + Either defaultValuesValidation = validatePropertyDefaultValue((AttributeDefinition)newAttributeDef, eitherAllDataTypes); if (defaultValuesValidation.isRight()) { return Either.right(defaultValuesValidation.right().value()); } - handleDefaultValue(newAttributeDef, eitherAllDataTypes); + handleDefaultValue((AttributeDefinition)newAttributeDef, eitherAllDataTypes); // add the new attribute to resource on graph // need to get StorageOpaerationStatus and convert to ActionStatus from // componentsUtils - Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); + Either either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef); if (either.isRight()) { result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName())); return result; @@ -137,7 +138,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } - private boolean isAttributeExist(List attributes, String resourceUid, String propertyName) { + private boolean isAttributeExist(List attributes, String resourceUid, String propertyName) { boolean isExist = false; if (attributes != null) { isExist = attributes.stream().anyMatch(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid)); @@ -152,7 +153,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either getAttribute(String resourceId, String attributeId, String userId) { + public Either getAttribute(String resourceId, String attributeId, String userId) { validateUserExists(userId); @@ -163,15 +164,14 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } Resource resource = status.left().value(); - List attributes = resource.getAttributes(); + List attributes = resource.getAttributes(); if (attributes == null) { return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")); } else { // verify attribute exist in resource - Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && att.getParentUniqueId().equals(resourceId)).findAny(); - return optionalAtt.>map(Either::left).orElseGet(() -> Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""))); + Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && resourceId.equals(att.getParentUniqueId())).findAny(); + return optionalAtt.>map(Either::left).orElseGet(() -> Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""))); } - } /** @@ -183,8 +183,8 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either updateAttribute(String resourceId, String attributeId, PropertyDefinition newAttDef, String userId) { - Either result = null; + public Either updateAttribute(String resourceId, String attributeId, AttributeDataDefinition newAttDef, String userId) { + Either result = null; StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { @@ -206,27 +206,26 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } // verify attribute exist in resource - Either eitherAttribute = getAttribute(resourceId, attributeId, userId); + Either eitherAttribute = getAttribute(resourceId, attributeId, userId); if (eitherAttribute.isRight()) { return Either.right(eitherAttribute.right().value()); } Map eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); // validate attribute default values - Either defaultValuesValidation = validatePropertyDefaultValue(newAttDef, eitherAllDataTypes); + Either defaultValuesValidation = validatePropertyDefaultValue((AttributeDefinition)newAttDef, eitherAllDataTypes); if (defaultValuesValidation.isRight()) { return Either.right(defaultValuesValidation.right().value()); } - // add the new property to resource on graph - StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty(newAttDef, eitherAllDataTypes); + // add the new property to resource on graph + StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty((AttributeDefinition)newAttDef, eitherAllDataTypes); if (validateAndUpdateAttribute != StorageOperationStatus.OK) { log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute); result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName())); } - - Either eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); + Either eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef); if (eitherAttUpdate.isRight()) { log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value()); @@ -251,9 +250,9 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either deleteAttribute(String resourceId, String attributeId, String userId) { + public Either deleteAttribute(String resourceId, String attributeId, String userId) { - Either result = null; + Either result = null; validateUserExists(userId); @@ -278,7 +277,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } // verify attribute exist in resource - Either eitherAttributeExist = getAttribute(resourceId, attributeId, userId); + Either eitherAttributeExist = getAttribute(resourceId, attributeId, userId); if (eitherAttributeExist.isRight()) { return Either.right(eitherAttributeExist.right().value()); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java index 4ac3815a2b..ba1500c9be 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentBusinessLogic.java @@ -49,6 +49,7 @@ import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.FilterKeyEnum; @@ -58,6 +59,7 @@ import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.facade.operations.CatalogOperation; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapReqDef; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; @@ -879,7 +881,7 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { clonedComponent.setDerivedFromGenericVersion(currentGenericVersion); } - private Either, String> validateNoConflictingProperties(List currentList, List upgradedList) { + private Either, String> validateNoConflictingProperties(List currentList, List upgradedList) { Map currentMap = ToscaDataDefinition.listToMapByName(currentList); Map upgradedMap = ToscaDataDefinition.listToMapByName(upgradedList); return ToscaDataDefinition.mergeDataMaps(upgradedMap, currentMap, true); @@ -888,15 +890,16 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { private boolean shouldUpgradeNodeType(Component componentToCheckOut, Resource latestGeneric){ List genericTypeProps = latestGeneric.getProperties(); - Either, String> validMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties()); - if (validMerge.isRight()) { - log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + Either, String> validPropertiesMerge = validateNoConflictingProperties(genericTypeProps, ((Resource)componentToCheckOut).getProperties()); + if (validPropertiesMerge.isRight()) { + log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validPropertiesMerge.right().value()); return false; } - List genericTypeAttributes = latestGeneric.getAttributes(); - validMerge = validateNoConflictingProperties(genericTypeAttributes, ((Resource)componentToCheckOut).getAttributes()); - if (validMerge.isRight()) { - log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validMerge.right().value()); + List genericTypeAttributes = latestGeneric.getAttributes(); + final Either, String> validAttributesMerge = validateNoConflictingProperties( + genericTypeAttributes, ((Resource) componentToCheckOut).getAttributes()); + if (validAttributesMerge.isRight()) { + log.debug("attribute {} cannot be overriden, check out performed without upgrading to latest generic", validAttributesMerge.right().value()); return false; } return true; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java index b0c9b308ab..e616ff87d3 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogic.java @@ -82,6 +82,7 @@ import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; @@ -133,7 +134,7 @@ import org.springframework.beans.factory.annotation.Autowired; @org.springframework.stereotype.Component public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { - private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName()); + private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class); private static final String VF_MODULE = "org.openecomp.groups.VfModule"; private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph"; private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech"; @@ -2885,14 +2886,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.info("start to copy component instance with attributes"); - List sourceAttributeList = null; + List sourceAttributeList = null; if (sourceComponent.getComponentInstancesAttributes() != null && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) { sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId); log.info("sourceAttributes {}"); } - List destAttributeList = null; + List destAttributeList = null; if (destComponent.getComponentInstancesAttributes() != null && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) { destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId); @@ -2901,18 +2902,18 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { if (null != sourceAttributeList && null != destAttributeList) { log.info("set attribute"); - for (ComponentInstanceProperty sourceAttribute : sourceAttributeList) { + for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) { String sourceAttributeName = sourceAttribute.getName(); - for (ComponentInstanceProperty destAttribute : destAttributeList) { + for (ComponentInstanceAttribute destAttribute : destAttributeList) { if (sourceAttributeName.equals(destAttribute.getName())) { - if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) { +// if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) { log.debug("Start to copy the attribute exists {}", sourceAttributeName); sourceAttribute.setUniqueId( UniqueIdBuilder.buildResourceInstanceUniuqeId( "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName)); - Either updateAttributeValueEither = + Either updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId); @@ -2923,7 +2924,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { "Failed to paste component instance to the canvas, attribute copy")); } break; - } +// } } } } @@ -2932,13 +2933,13 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return Either.left(COPY_COMPONENT_INSTANCE_OK); } - private Either createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum, + private Either createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, - ComponentInstanceProperty attribute, + ComponentInstanceAttribute attribute, String userId) { - Either resultOp = null; + Either resultOp = null; validateUserExists(userId); @@ -2989,10 +2990,8 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - List instanceAttributes = containerComponent. - getComponentInstancesAttributes().get(resourceInstanceId); - Optional instanceAttribute = - instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny(); + List instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId); + Optional instanceAttribute = instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny(); StorageOperationStatus status; if (instanceAttribute.isPresent()) { @@ -3024,9 +3023,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } resultOp = Either.left(attribute); return resultOp; - - - } private Either updateComponentInstanceProperty(String containerComponentId, diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java index cc6b359098..01698fa662 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ImportUtils.java @@ -27,15 +27,19 @@ import com.google.gson.reflect.TypeToken; import fj.data.Either; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.tinkerpop.gremlin.structure.T; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.Annotation; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.AnnotationTypeDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; @@ -86,7 +90,7 @@ public final class ImportUtils { private static final CustomResolver customResolver = new CustomResolver(); private static final Yaml strictYamlLoader = new YamlLoader().getStrictYamlLoader(); - protected static ComponentsUtils componentsUtils; + private static ComponentsUtils componentsUtils; private static final Logger log = Logger.getLogger(ImportUtils.class); @@ -95,7 +99,7 @@ public final class ImportUtils { @Autowired public static void setComponentsUtils(ComponentsUtils componentsUtils) { - ImportUtils.componentsUtils = componentsUtils; + componentsUtils = componentsUtils; } private static class CustomResolver extends Resolver { @@ -112,7 +116,6 @@ public final class ImportUtils { } } - private static void buildMap(Map output, Map map) { for (Entry entry : map.entrySet()) { String key = entry.getKey(); @@ -186,9 +189,9 @@ public final class ImportUtils { @SuppressWarnings("unchecked") private static void handleElementNameNotFound(String elementName, Object elementValue, ToscaElementTypeEnum elementType, List returnedList) { if (elementValue instanceof Map) { - ImportUtils.findToscaElements((Map) elementValue, elementName, elementType, returnedList); + findToscaElements((Map) elementValue, elementName, elementType, returnedList); } else if (elementValue instanceof List) { - ImportUtils.findAllToscaElementsInList((List) elementValue, elementName, elementType, returnedList); + findAllToscaElementsInList((List) elementValue, elementName, elementType, returnedList); } } @@ -209,13 +212,13 @@ public final class ImportUtils { if (elementType == ToscaElementTypeEnum.MAP || elementType == ToscaElementTypeEnum.ALL) { returnedList.add(elementValue); } - ImportUtils.findToscaElements((Map) elementValue, elementName, elementType, returnedList); + findToscaElements((Map) elementValue, elementName, elementType, returnedList); } else if (elementValue instanceof List) { if (elementType == ToscaElementTypeEnum.LIST || elementType == ToscaElementTypeEnum.ALL) { returnedList.add(elementValue); } - ImportUtils.findAllToscaElementsInList((List) elementValue, elementName, elementType, returnedList); + findAllToscaElementsInList((List) elementValue, elementName, elementType, returnedList); } // For Integer, Double etc... @@ -230,7 +233,7 @@ public final class ImportUtils { public static Either findToscaElement(Map toscaJson, TypeUtils.ToscaTagNamesEnum elementName, ToscaElementTypeEnum elementType) { List foundElements = new ArrayList<>(); - ImportUtils.findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements); + findToscaElements(toscaJson, elementName.getElementName(), elementType, foundElements); if (!isEmpty(foundElements)) { return Either.left(foundElements.get(0)); } @@ -398,24 +401,21 @@ public final class ImportUtils { return propertyDef; } - private static void setJsonStringField(Map propertyValue, ToscaTagNamesEnum elementName, String type, Consumer setter) { - Either eitherValue = ImportUtils.findToscaElement(propertyValue, elementName, ToscaElementTypeEnum.ALL); + Either eitherValue = findToscaElement(propertyValue, elementName, ToscaElementTypeEnum.ALL); if (eitherValue.isLeft()) { String propertyJsonStringValue = getPropertyJsonStringValue(eitherValue.left().value(), type); setter.accept(propertyJsonStringValue); } } - - public static Annotation createModuleAnnotation(Map annotationMap, AnnotationTypeOperations annotationTypeOperations) { String parsedAnnotationType = findFirstToscaStringElement(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE).left().value(); AnnotationTypeDefinition annotationTypeObject = annotationTypeOperations.getLatestType(parsedAnnotationType); if (annotationTypeObject != null) { Annotation annotation = new Annotation(); - ImportUtils.setField(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE, annotation::setType); - ImportUtils.setField(annotationMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, annotation::setDescription); + setField(annotationMap, TypeUtils.ToscaTagNamesEnum.TYPE, annotation::setType); + setField(annotationMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, annotation::setDescription); Either, ResultStatusEnum> properties = getProperties(annotationMap); modifyPropertiesKeysToProperForm(properties, annotation); return annotation; @@ -454,26 +454,25 @@ public final class ImportUtils { public static InputDefinition createModuleInput(Map inputValue, AnnotationTypeOperations annotationTypeOperations) { InputDefinition inputDef = new InputDefinition(); - ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.TYPE, inputDef::setType); - ImportUtils.setFieldBoolean(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req))); - ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, inputDef::setDescription); + setField(inputValue, TypeUtils.ToscaTagNamesEnum.TYPE, inputDef::setType); + setFieldBoolean(inputValue, ToscaTagNamesEnum.REQUIRED, req -> inputDef.setRequired(Boolean.parseBoolean(req))); + setField(inputValue, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, inputDef::setDescription); setJsonStringField(inputValue, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, inputDef.getType(), inputDef::setDefaultValue); - ImportUtils.setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass))); - ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.STATUS, inputDef::setStatus); - ImportUtils.setField(inputValue, TypeUtils.ToscaTagNamesEnum.LABEL, inputDef::setLabel); - ImportUtils.setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden))); - ImportUtils.setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IMMUTABLE, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable))); + setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IS_PASSWORD, pass -> inputDef.setPassword(Boolean.parseBoolean(pass))); + setField(inputValue, TypeUtils.ToscaTagNamesEnum.STATUS, inputDef::setStatus); + setField(inputValue, TypeUtils.ToscaTagNamesEnum.LABEL, inputDef::setLabel); + setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.HIDDEN, hidden -> inputDef.setHidden(Boolean.parseBoolean(hidden))); + setFieldBoolean(inputValue, TypeUtils.ToscaTagNamesEnum.IMMUTABLE, immutable -> inputDef.setImmutable(Boolean.parseBoolean(immutable))); - ImportUtils.setScheme(inputValue, inputDef); - ImportUtils.setPropertyConstraints(inputValue, inputDef); + setScheme(inputValue, inputDef); + setPropertyConstraints(inputValue, inputDef); return parseAnnotationsAndAddItToInput(inputDef, inputValue, annotationTypeOperations); } - public static InputDefinition parseAnnotationsAndAddItToInput(InputDefinition inputDef, Map inputValue, AnnotationTypeOperations annotationTypeOperations){ Function elementGenByName = ImportUtils::createAnnotation; Function, Annotation> func = annotation -> createModuleAnnotation(annotation, annotationTypeOperations); @@ -489,30 +488,29 @@ public final class ImportUtils { return inputDef; } + public static AttributeDefinition createModuleAttribute(Map attributeMap) { - public static PropertyDefinition createModuleAttribute(Map attributeMap) { - - PropertyDefinition attributeDef = new PropertyDefinition(); + AttributeDefinition attributeDef = new AttributeDefinition(); setField(attributeMap, TypeUtils.ToscaTagNamesEnum.TYPE, attributeDef::setType); setField(attributeMap, TypeUtils.ToscaTagNamesEnum.DESCRIPTION, attributeDef::setDescription); setField(attributeMap, TypeUtils.ToscaTagNamesEnum.STATUS, attributeDef::setStatus); - setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, attributeDef.getType(), attributeDef::setDefaultValue); - setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.VALUE, attributeDef.getType(), attributeDef::setValue); + setJsonStringField(attributeMap, TypeUtils.ToscaTagNamesEnum.DEFAULT_VALUE, attributeDef.getType(), attributeDef::set_default); setScheme(attributeMap, attributeDef); return attributeDef; } - private static void setScheme(Map propertyValue, PropertyDefinition propertyDefinition) { + private static void setScheme(Map propertyValue, + ToscaDataDefinition toscaDataDefinition) { Either schemaElementRes = findSchemaElement(propertyValue); if (schemaElementRes.isLeft()) { SchemaDefinition schemaDef = getSchema(schemaElementRes.left().value()); - propertyDefinition.setSchema(schemaDef); + toscaDataDefinition.setSchema(schemaDef); } } - private static Either findSchemaElement(Map propertyValue) { + private static Either findSchemaElement(Map propertyValue) { return findToscaElement(propertyValue, TypeUtils.ToscaTagNamesEnum.ENTRY_SCHEMA, ToscaElementTypeEnum.ALL); } @@ -546,8 +544,8 @@ public final class ImportUtils { } - - public static Either, ResultStatusEnum> getProperties(Map toscaJson) { + public static Either, ResultStatusEnum> getProperties( + Map toscaJson) { Function elementGenByName = ImportUtils::createProperties; Function, PropertyDefinition> func = ImportUtils::createModuleProperty; @@ -555,25 +553,31 @@ public final class ImportUtils { } - public static Either, ResultStatusEnum> getInputs(Map toscaJson, AnnotationTypeOperations annotationTypeOperations) { + public static Either, ResultStatusEnum> getInputs(Map toscaJson, + AnnotationTypeOperations annotationTypeOperations) { Function elementGenByName = ImportUtils::createInputs; - Function, InputDefinition> func = object -> createModuleInput(object, annotationTypeOperations); + Function, InputDefinition> func = object -> createModuleInput(object, + annotationTypeOperations); return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.INPUTS, elementGenByName, func); } - public static Either, ResultStatusEnum> getAttributes(Map toscaJson) { - Function elementGenByName = ImportUtils::createAttribute; - Function, PropertyDefinition> func = ImportUtils::createModuleAttribute; + public static Either, ResultStatusEnum> getAttributes( + Map toscaJson) { + Function elementGenByName = ImportUtils::createAttribute; + Function, AttributeDataDefinition> func = ImportUtils::createModuleAttribute; return getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.ATTRIBUTES, elementGenByName, func); } - public static Either, ResultStatusEnum> getElements(Map toscaJson, TypeUtils.ToscaTagNamesEnum elementTagName, Function elementGenByName, + public static Either, ResultStatusEnum> getElements(Map toscaJson, + TypeUtils.ToscaTagNamesEnum elementTagName, + Function elementGenByName, Function, T> func) { Either, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); - Either, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, elementTagName); + Either, ResultStatusEnum> toscaAttributes = findFirstToscaMapElement(toscaJson, + elementTagName); if (toscaAttributes.isLeft()) { Map jsonAttributes = toscaAttributes.left().value(); Map moduleAttributes = new HashMap<>(); @@ -583,7 +587,7 @@ public final class ImportUtils { if (attributeNameValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") T attribute = func.apply((Map) attributeNameValue.getValue()); - if (attribute != null){ + if (attribute != null) { moduleAttributes.put(String.valueOf(attributeNameValue.getKey()), attribute); } } @@ -601,8 +605,8 @@ public final class ImportUtils { } - private static PropertyDefinition createAttribute(String name) { - PropertyDefinition attribute = new PropertyDefinition(); + private static AttributeDefinition createAttribute(String name) { + AttributeDefinition attribute = new AttributeDefinition(); attribute.setName(name); return attribute; @@ -615,8 +619,6 @@ public final class ImportUtils { return property; } - - private static InputDefinition createInputs(String name) { InputDefinition input = new InputDefinition(); @@ -630,8 +632,6 @@ public final class ImportUtils { return annotation; } - - public static Either, ResultStatusEnum> getHeatParameters(Map heatData, String artifactType) { Either, ResultStatusEnum> eitherResult = Either.right(ResultStatusEnum.ELEMENT_NOT_FOUND); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java index 6e3019c0c3..35a0761ff1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java @@ -94,6 +94,7 @@ import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; @@ -109,6 +110,7 @@ import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.info.NodeTypeInfoToUpdateArtifacts; import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.CapabilityRequirementRelationship; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; @@ -2617,8 +2619,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { resource.getUniqueId(), yamlName); loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"No instances found in the resource: {}, is empty, yaml template file name: {}",resource.getName(),yamlName); BeEcompErrorManager.getInstance() - .logInternalDataError("createResourceInstancesRelations", - "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR); + .logInternalDataError("createResourceInstancesRelations", + "No instances found in a resource or nn yaml template. ", ErrorSeverity.ERROR); throw new ByActionStatusComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } Map> instProperties = new HashMap<>(); @@ -2626,17 +2628,17 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map>> instRequirements = new HashMap<>(); Map> instDeploymentArtifacts = new HashMap<>(); Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); List relations = new ArrayList<>(); Map> instInputs = new HashMap<>(); log.debug("#createResourceInstancesRelations - Before get all datatypes. "); - Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); + Either, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); if (allDataTypes.isRight()) { JanusGraphOperationStatus status = allDataTypes.right() - .value(); + .value(); BeEcompErrorManager.getInstance() - .logInternalFlowError("UpdatePropertyValueOnComponentInstance", + .logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); loggerSupportability.log(LoggerSupportabilityActions.CREATE_RELATIONS,resource.getComponentMetadataForSupportLog(), StatusCode.ERROR,"ERROR while update property value on instance. Status is: "+status); @@ -2683,32 +2685,39 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map>> instCapabilities, Map>> instRequirements, Map> instDeploymentArtifacts, - Map> instArtifacts, Map> instProperties, Map> instInputs, Map> instAttributes) { + Map> instArtifacts, Map> instProperties, Map> instInputs, + Map> instAttributes) { Optional foundInstance = findInstance(oldResource, instance); - if(foundInstance.isPresent()){ - if(MapUtils.isNotEmpty(foundInstance.get().getCapabilities())){ + if (foundInstance.isPresent()) { + if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) { instCapabilities.put(instance, foundInstance.get().getCapabilities()); } - if(MapUtils.isNotEmpty(foundInstance.get().getRequirements())){ + if (MapUtils.isNotEmpty(foundInstance.get().getRequirements())) { instRequirements.put(instance, foundInstance.get().getRequirements()); } - if(MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())){ + if (MapUtils.isNotEmpty(foundInstance.get().getDeploymentArtifacts())) { instDeploymentArtifacts.put(instance.getUniqueId(), foundInstance.get().getDeploymentArtifacts()); } if(MapUtils.isNotEmpty(foundInstance.get().getArtifacts())){ instArtifacts.put(instance.getUniqueId(), foundInstance.get().getArtifacts()); } - if(MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) && - CollectionUtils.isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))){ - instProperties.put(instance.getUniqueId(), oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId())); + if (MapUtils.isNotEmpty(oldResource.getComponentInstancesProperties()) && + CollectionUtils + .isNotEmpty(oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId()))) { + instProperties.put(instance.getUniqueId(), + oldResource.getComponentInstancesProperties().get(foundInstance.get().getUniqueId())); } - if(MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) && - CollectionUtils.isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))){ - instInputs.put(instance.getUniqueId(), oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId())); + if (MapUtils.isNotEmpty(oldResource.getComponentInstancesInputs()) && + CollectionUtils + .isNotEmpty(oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId()))) { + instInputs.put(instance.getUniqueId(), + oldResource.getComponentInstancesInputs().get(foundInstance.get().getUniqueId())); } if(MapUtils.isNotEmpty(oldResource.getComponentInstancesAttributes()) && CollectionUtils.isNotEmpty(oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()))){ - instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(PropertyDefinition::new).collect(toList())); + instAttributes.put(instance.getUniqueId(), oldResource.getComponentInstancesAttributes().get(foundInstance.get().getUniqueId()).stream().map(AttributeDefinition::new).collect(toList())); } } } @@ -2735,14 +2744,15 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, - Map> instAttributes) { + Map> instAttributes) { StorageOperationStatus addArtToInst; addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, - resource); + resource); if (addArtToInst != StorageOperationStatus.OK && addArtToInst != StorageOperationStatus.NOT_FOUND) { log.debug("failed to associate attributes of resource {} status is {}", resource.getUniqueId(), - addArtToInst); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), yamlName); + addArtToInst); + throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(addArtToInst), + yamlName); } } @@ -2890,7 +2900,8 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map>> instRequirements, Map> instDeploymentArtifacts, Map> instArtifacts, - Map> instAttributes, Map originCompMap, + Map> instAttributes, + Map originCompMap, Map> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) { Optional currentCompInstanceOpt = componentInstancesList.stream() @@ -2914,24 +2925,22 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } if (isNotEmpty(originResource.getCapabilities())) { processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, - currentCompInstance, originResource); + currentCompInstance, originResource); } if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts() - .isEmpty()) { + .isEmpty()) { instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); } - if (originResource.getArtifacts() != null && !originResource.getArtifacts() - .isEmpty()) { + if (originResource.getArtifacts() != null && !originResource.getArtifacts().isEmpty()) { instArtifacts.put(resourceInstanceId, originResource.getArtifacts()); } - if (originResource.getAttributes() != null && !originResource.getAttributes() - .isEmpty()) { + if (originResource.getAttributes() != null && !originResource.getAttributes().isEmpty()) { instAttributes.put(resourceInstanceId, originResource.getAttributes()); } if (originResource.getResourceType() != ResourceTypeEnum.CVFC) { ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, resource, - originResource, currentCompInstance, instProperties, allDataTypes.left() - .value()); + originResource, currentCompInstance, instProperties, allDataTypes.left() + .value()); if (addPropertiesValueToRiRes.getStatus() != 200) { throw new ByResponseFormatComponentException(addPropertiesValueToRiRes); } @@ -3982,11 +3991,9 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { mergeOldResourceMetadataWithNew(oldResource, newResource); validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); - validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, - AuditingActionEnum.IMPORT_RESOURCE, inTransaction); + validateCapabilityTypesCreate(user, getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction); // contact info normalization - newResource.setContactId(newResource.getContactId() - .toLowerCase()); + newResource.setContactId(newResource.getContactId().toLowerCase()); PropertyConstraintsUtils.validatePropertiesConstraints(newResource, oldResource); // non-updatable fields newResource.setCreatorUserId(user.getUserId()); @@ -4008,58 +4015,56 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } newResource.setAbstract(oldResource.isAbstract()); - if (newResource.getDerivedFrom() == null || newResource.getDerivedFrom() - .isEmpty()) { + if (CollectionUtils.isEmpty(newResource.getDerivedFrom())) { newResource.setDerivedFrom(oldResource.getDerivedFrom()); } - if (newResource.getDerivedFromGenericType() == null || newResource.getDerivedFromGenericType() - .isEmpty()) { + if (StringUtils.isEmpty(newResource.getDerivedFromGenericType())) { newResource.setDerivedFromGenericType(oldResource.getDerivedFromGenericType()); } - if (newResource.getDerivedFromGenericVersion() == null || newResource.getDerivedFromGenericVersion() - .isEmpty()) { + if (StringUtils.isEmpty(newResource.getDerivedFromGenericVersion())) { newResource.setDerivedFromGenericVersion(oldResource.getDerivedFromGenericVersion()); } // add for new) // created without tosca artifacts - add the placeholders - if (newResource.getToscaArtifacts() == null || newResource.getToscaArtifacts() - .isEmpty()) { + if (MapUtils.isEmpty(newResource.getToscaArtifacts())) { setToscaArtifactsPlaceHolders(newResource, user); } - if (newResource.getInterfaces() == null || newResource.getInterfaces().isEmpty()) { + if (MapUtils.isEmpty(newResource.getInterfaces())) { newResource.setInterfaces(oldResource.getInterfaces()); } + if (CollectionUtils.isEmpty(newResource.getAttributes())) { + newResource.setAttributes(oldResource.getAttributes()); + } - if (CollectionUtils.isEmpty(newResource.getProperties())) { - newResource.setProperties(oldResource.getProperties()); - } + if (CollectionUtils.isEmpty(newResource.getProperties())) { + newResource.setProperties(oldResource.getProperties()); + } - Either overrideResource = toscaOperationFacade - .overrideComponent(newResource, oldResource); + Either overrideResource = toscaOperationFacade.overrideComponent(newResource, oldResource); if (overrideResource.isRight()) { ResponseFormat responseFormat = componentsUtils - .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right() - .value()), newResource); + .getResponseFormatByResource(componentsUtils.convertFromStorageResponse(overrideResource.right() + .value()), newResource); componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE); throwComponentException(responseFormat); } updateCatalog(overrideResource.left() - .value(), ChangeTypeEnum.LIFECYCLE); + .value(), ChangeTypeEnum.LIFECYCLE); log.debug("Resource updated successfully!!!"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK); componentsUtils.auditResource(responseFormat, user, newResource, AuditingActionEnum.IMPORT_RESOURCE, - ResourceVersionInfo.newBuilder() - .state(oldResource.getLifecycleState() - .name()) - .version(oldResource.getVersion()) - .build()); + ResourceVersionInfo.newBuilder() + .state(oldResource.getLifecycleState() + .name()) + .version(oldResource.getVersion()) + .build()); resourcePair = new ImmutablePair<>(overrideResource.left() - .value(), ActionStatus.OK); + .value(), ActionStatus.OK); return resourcePair; } finally { if (resourcePair == null) { @@ -4439,7 +4444,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { componentsUtils.auditResource(responseFormat, user, resource, actionEnum); throw e; } finally { - if (!inTransaction) { + if (!inTransaction) { graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java index 46942d96d4..1a0dfaa9fd 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceImportManager.java @@ -23,6 +23,7 @@ package org.openecomp.sdc.be.components.impl; import static org.openecomp.sdc.be.components.impl.ImportUtils.Constants.QUOTE; +import static org.openecomp.sdc.be.utils.TypeUtils.setField; import fj.data.Either; import java.util.LinkedHashMap; @@ -43,6 +44,7 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition; @@ -53,7 +55,9 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.CapabilityDefinition; +import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; @@ -100,6 +104,7 @@ import java.util.stream.Collectors; @Component("resourceImportManager") public class ResourceImportManager { + private static final Logger log = Logger.getLogger(ResourceImportManager.class); static final Pattern PROPERTY_NAME_PATTERN_IGNORE_LENGTH = Pattern.compile("[\\w\\-\\_\\d\\:]+"); @@ -136,27 +141,46 @@ public class ResourceImportManager { this.toscaOperationFacade = toscaOperationFacade; } - public ImmutablePair importNormativeResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { + public ImmutablePair importNormativeResource(String resourceYml, + UploadResourceInfo resourceMetaData, + User creator, boolean createNewVersion, + boolean needLock) { LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); lifecycleChangeInfo.setUserRemarks("certification on import"); - Function validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + Function validator = resource -> resourceBusinessLogic + .validatePropertiesDefaultValues(resource); - return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, + createNewVersion, needLock, null, null, false, null, null, false); } - public ImmutablePair importNormativeResourceFromCsar(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean createNewVersion, boolean needLock) { + public ImmutablePair importNormativeResourceFromCsar(String resourceYml, + UploadResourceInfo resourceMetaData, + User creator, boolean createNewVersion, + boolean needLock) { LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction(); lifecycleChangeInfo.setUserRemarks("certification on import"); - Function validator = resource -> resourceBusinessLogic.validatePropertiesDefaultValues(resource); + Function validator = resource -> resourceBusinessLogic + .validatePropertiesDefaultValues(resource); - return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, createNewVersion, needLock, null, null, false, null, null, false); + return importCertifiedResource(resourceYml, resourceMetaData, creator, validator, lifecycleChangeInfo, false, + createNewVersion, needLock, null, null, false, null, null, false); } - public ImmutablePair importCertifiedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, + public ImmutablePair importCertifiedResource(String resourceYml, + UploadResourceInfo resourceMetaData, + User creator, Function validationFunction, - LifecycleChangeInfoWithAction lifecycleChangeInfo, boolean isInTransaction, boolean createNewVersion, boolean needLock, Map> nodeTypeArtifactsToHandle, List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, String nodeName, boolean isNested) { + LifecycleChangeInfoWithAction lifecycleChangeInfo, + boolean isInTransaction, + boolean createNewVersion, boolean needLock, + Map> nodeTypeArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, + boolean forceCertificationAllowed, + CsarInfo csarInfo, String nodeName, + boolean isNested) { Resource resource = new Resource(); ImmutablePair responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); Either, ResponseFormat> response = Either.left(responsePair); @@ -170,32 +194,38 @@ public class ResourceImportManager { populateResourceFromYaml(resourceYml, resource); Boolean isValidResource = validationFunction.apply(resource); - if (!createNewVersion) { - Either latestByName = toscaOperationFacade.getLatestByName(resource.getName()); - if (latestByName.isLeft()) { - throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, resource.getName()); - } + if (!createNewVersion) { + Either latestByName = toscaOperationFacade + .getLatestByName(resource.getName()); + if (latestByName.isLeft()) { + throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, + resource.getName()); } - resource = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, isNested).left; - Resource changeStateResponse; - - if (nodeTypeArtifactsToHandle != null && !nodeTypeArtifactsToHandle.isEmpty()) { - Either, ResponseFormat> handleNodeTypeArtifactsRes = - resourceBusinessLogic.handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, creator, isInTransaction, false); - if (handleNodeTypeArtifactsRes.isRight()) { - //TODO: should be used more correct action - throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); - } + } + resource = resourceBusinessLogic + .createOrUpdateResourceByImport(resource, creator, true, isInTransaction, needLock, csarInfo, nodeName, + isNested).left; + Resource changeStateResponse; + + if (nodeTypeArtifactsToHandle != null && !nodeTypeArtifactsToHandle.isEmpty()) { + Either, ResponseFormat> handleNodeTypeArtifactsRes = + resourceBusinessLogic + .handleNodeTypeArtifacts(resource, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, + creator, isInTransaction, false); + if (handleNodeTypeArtifactsRes.isRight()) { + //TODO: should be used more correct action + throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } - latestCertifiedResourceId = getLatestCertifiedResourceId(resource); - changeStateResponse = resourceBusinessLogic.propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, forceCertificationAllowed); - responsePair = new ImmutablePair<>(changeStateResponse, response.left() - .value().right); - } - catch (RuntimeException e) { + } + latestCertifiedResourceId = getLatestCertifiedResourceId(resource); + changeStateResponse = resourceBusinessLogic + .propagateStateToCertified(creator, resource, lifecycleChangeInfo, isInTransaction, needLock, + forceCertificationAllowed); + responsePair = new ImmutablePair<>(changeStateResponse, response.left() + .value().right); + } catch (RuntimeException e) { handleImportResourceException(resourceMetaData, creator, true, e); - } - finally { + } finally { if (latestCertifiedResourceId != null && needLock) { log.debug("unlock resource {}", latestCertifiedResourceId); graphLockOperation.unlockComponent(latestCertifiedResourceId, NodeTypeEnum.Resource); @@ -206,9 +236,11 @@ public class ResourceImportManager { } private ResponseFormat getResponseFormatFromComponentException(RuntimeException e) { - if(e instanceof ComponentException){ + if (e instanceof ComponentException) { return ((ComponentException) e).getResponseFormat() == null ? - componentsUtils.getResponseFormat(((ComponentException) e).getActionStatus(), ((ComponentException) e).getParams()) : + componentsUtils + .getResponseFormat(((ComponentException) e).getActionStatus(), ((ComponentException) e).getParams()) + : ((ComponentException) e).getResponseFormat(); } return null; @@ -225,8 +257,7 @@ public class ResourceImportManager { } } return allVersions.get(String.valueOf(latestCertifiedVersion)); - } - else { + } else { return null; } } @@ -250,7 +281,9 @@ public class ResourceImportManager { } } - public ImmutablePair importUserDefinedResource(String resourceYml, UploadResourceInfo resourceMetaData, User creator, boolean isInTransaction) { + public ImmutablePair importUserDefinedResource(String resourceYml, + UploadResourceInfo resourceMetaData, + User creator, boolean isInTransaction) { Resource resource = new Resource(); ImmutablePair responsePair = new ImmutablePair<>(resource, ActionStatus.CREATED); @@ -271,10 +304,9 @@ public class ResourceImportManager { Boolean validatePropertiesTypes = resourceBusinessLogic.validatePropertiesDefaultValues(resource); responsePair = resourceBusinessLogic.createOrUpdateResourceByImport(resource, creator, - false, isInTransaction, true, null, null, false); + false, isInTransaction, true, null, null, false); - } - catch (RuntimeException e) { + } catch (RuntimeException e) { handleImportResourceException(resourceMetaData, creator, false, e); } return responsePair; @@ -289,9 +321,11 @@ public class ResourceImportManager { Map toscaJson = toscaJsonAll; // Checks if exist and builds the node_types map - if (toscaJsonAll.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()) && resource.getResourceType() != ResourceTypeEnum.CVFC) { + if (toscaJsonAll.containsKey(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName()) + && resource.getResourceType() != ResourceTypeEnum.CVFC) { toscaJson = new HashMap<>(); - toscaJson.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), toscaJsonAll.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName())); + toscaJson.put(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName(), + toscaJsonAll.get(TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName())); } // Derived From Resource parentResource = setDerivedFrom(toscaJson, resource); @@ -303,15 +337,15 @@ public class ResourceImportManager { setProperties(toscaJson, resource); setRequirements(toscaJson, resource, parentResource); setInterfaceLifecycle(toscaJson, resource); - } - else { + } else { throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } } private void setToscaResourceName(Map toscaJson, Resource resource) { - Either, ResultStatusEnum> toscaElement = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); + Either, ResultStatusEnum> toscaElement = ImportUtils + .findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.NODE_TYPES); if (toscaElement.isLeft() || toscaElement.left().value().size() == 1) { String toscaResourceName = toscaElement.left().value().keySet().iterator().next(); resource.setToscaResourceName(toscaResourceName); @@ -319,7 +353,8 @@ public class ResourceImportManager { } private void setInterfaceLifecycle(Map toscaJson, Resource resource) { - Either, ResultStatusEnum> toscaInterfaces = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.INTERFACES); + Either, ResultStatusEnum> toscaInterfaces = ImportUtils + .findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.INTERFACES); if (toscaInterfaces.isLeft()) { Map jsonInterfaces = toscaInterfaces.left().value(); Map moduleInterfaces = new HashMap<>(); @@ -327,11 +362,11 @@ public class ResourceImportManager { while (interfacesNameValue.hasNext()) { Entry interfaceNameValue = interfacesNameValue.next(); Either eitherInterface = createModuleInterface(interfaceNameValue - .getValue(), resource); + .getValue(), resource); if (eitherInterface.isRight()) { - log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), resource.getName()); - } - else { + log.info("error when creating interface:{}, for resource:{}", interfaceNameValue.getKey(), + resource.getName()); + } else { moduleInterfaces.put(interfaceNameValue.getKey(), eitherInterface.left().value()); } @@ -342,7 +377,8 @@ public class ResourceImportManager { } } - private Either createModuleInterface(Object interfaceJson, Resource resource) { + private Either createModuleInterface(Object interfaceJson, + Resource resource) { final InterfaceDefinition interf = new InterfaceDefinition(); Either result = Either.left(interf); @@ -384,8 +420,7 @@ public class ResourceImportManager { result = Either.right(ResultStatusEnum.GENERAL_ERROR); } - } - catch (Exception e) { + } catch (Exception e) { BeEcompErrorManager.getInstance().logBeSystemError("Import Resource- create interface"); log.debug("error when creating interface, message:{}", e.getMessage(), e); result = Either.right(ResultStatusEnum.GENERAL_ERROR); @@ -405,7 +440,8 @@ public class ResourceImportManager { return implementation; } - private ListDataDefinition handleInterfaceInput(final Map interfaceInputs) { + private ListDataDefinition handleInterfaceInput( + final Map interfaceInputs) { final ListDataDefinition inputs = new ListDataDefinition<>(); for (final Entry interfaceInput : interfaceInputs.entrySet()) { final OperationInputDefinition operationInput = new OperationInputDefinition(); @@ -446,52 +482,60 @@ public class ResourceImportManager { } private boolean entryIsInterfaceType(final Entry entry) { - if(entry.getKey().equals(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) { - if (entry.getValue() instanceof String) { - return true; - } - throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML); - } - return false; + if (entry.getKey().equals(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) { + if (entry.getValue() instanceof String) { + return true; + } + throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML); + } + return false; } - - private boolean entryContainsImplementationForAKnownOperation(final Entry entry, final String interfaceType) { - if (entry.getValue() instanceof Map && ((Map)entry.getValue()).containsKey(IMPLEMENTATION)) { - if (isAKnownOperation(interfaceType, entry.getKey())){ - return true; - } - throw new ByActionStatusComponentException(ActionStatus.INTERFACE_OPERATION_NOT_FOUND); - } - return false; + + private boolean entryContainsImplementationForAKnownOperation(final Entry entry, + final String interfaceType) { + if (entry.getValue() instanceof Map && ((Map) entry.getValue()).containsKey(IMPLEMENTATION)) { + if (isAKnownOperation(interfaceType, entry.getKey())) { + return true; + } + throw new ByActionStatusComponentException(ActionStatus.INTERFACE_OPERATION_NOT_FOUND); + } + return false; } - - private boolean isAKnownOperation(String interfaceType, String operation) { - Either, ResponseFormat> interfaceLifecycleTypes = interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(); - if (interfaceLifecycleTypes.isRight() || interfaceLifecycleTypes.left().value() == null) { - return false; - } - - for (Entry interfaceLifecycleType : interfaceLifecycleTypes.left().value().entrySet()) { - if (interfaceTypeAndOperationMatches(interfaceLifecycleType, interfaceType, operation)) { - return true; - } - } - return false; + + private boolean isAKnownOperation(String interfaceType, String operation) { + Either, ResponseFormat> interfaceLifecycleTypes = interfaceOperationBusinessLogic + .getAllInterfaceLifecycleTypes(); + if (interfaceLifecycleTypes.isRight() || interfaceLifecycleTypes.left().value() == null) { + return false; + } + + for (Entry interfaceLifecycleType : interfaceLifecycleTypes.left().value() + .entrySet()) { + if (interfaceTypeAndOperationMatches(interfaceLifecycleType, interfaceType, operation)) { + return true; + } + } + return false; } - - private boolean interfaceTypeAndOperationMatches(Entry interfaceLifecycleType, String interfaceType, String operation) { - if (interfaceLifecycleType.getKey().equalsIgnoreCase(interfaceType) && interfaceLifecycleType.getValue().getOperations() != null) { - for (String interfaceLifecycleTypeOperation : interfaceLifecycleType.getValue().getOperations().keySet()) { - if (interfaceLifecycleTypeOperation != null && interfaceLifecycleTypeOperation.equalsIgnoreCase(operation)){ - return true; - } - } - } - return false; + + private boolean interfaceTypeAndOperationMatches(Entry interfaceLifecycleType, + String interfaceType, String operation) { + if (interfaceLifecycleType.getKey().equalsIgnoreCase(interfaceType) + && interfaceLifecycleType.getValue().getOperations() != null) { + for (String interfaceLifecycleTypeOperation : interfaceLifecycleType.getValue().getOperations().keySet()) { + if (interfaceLifecycleTypeOperation != null && interfaceLifecycleTypeOperation + .equalsIgnoreCase(operation)) { + return true; + } + } + } + return false; } - private void setRequirements(Map toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null - Either, ResultStatusEnum> toscaRequirements = ImportUtils.findFirstToscaListElement(toscaJson, TypeUtils.ToscaTagNamesEnum.REQUIREMENTS); + private void setRequirements(Map toscaJson, Resource resource, + Resource parentResource) {// Note that parentResource can be null + Either, ResultStatusEnum> toscaRequirements = ImportUtils + .findFirstToscaListElement(toscaJson, TypeUtils.ToscaTagNamesEnum.REQUIREMENTS); if (toscaRequirements.isLeft()) { List jsonRequirements = toscaRequirements.left().value(); Map> moduleRequirements = new HashMap<>(); @@ -506,17 +550,19 @@ public class ResourceImportManager { String requirementName = requirementJsonWrapper.keySet().iterator().next(); String reqNameLowerCase = requirementName.toLowerCase(); if (reqNames.contains(reqNameLowerCase)) { - log.debug("More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", reqNameLowerCase); - throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "requirement", reqNameLowerCase); + log.debug( + "More than one requirement with same name {} (case-insensitive) in imported TOSCA file is invalid", + reqNameLowerCase); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, + "requirement", reqNameLowerCase); } reqNames.add(reqNameLowerCase); RequirementDefinition requirementDef = createRequirementFromImportFile(requirementJsonWrapper - .get(requirementName)); + .get(requirementName)); requirementDef.setName(requirementName); if (moduleRequirements.containsKey(requirementDef.getCapability())) { moduleRequirements.get(requirementDef.getCapability()).add(requirementDef); - } - else { + } else { List list = new ArrayList<>(); list.add(requirementDef); moduleRequirements.put(requirementDef.getCapability(), list); @@ -524,13 +570,15 @@ public class ResourceImportManager { // Validating against req/cap of "derived from" node Boolean validateVsParentCap = validateCapNameVsDerived(reqName2TypeMap, requirementDef - .getCapability(), requirementDef.getName()); + .getCapability(), requirementDef.getName()); if (!validateVsParentCap) { String parentResourceName = parentResource != null ? parentResource.getName() : ""; - log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), parentResourceName); - throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "requirement", requirementDef - .getName() - .toLowerCase(), parentResourceName); + log.debug("Requirement with name {} already exists in parent {}", requirementDef.getName(), + parentResourceName); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, + "requirement", requirementDef + .getName() + .toLowerCase(), parentResourceName); } } if (moduleRequirements.size() > 0) { @@ -538,7 +586,7 @@ public class ResourceImportManager { } } - } + } private RequirementDefinition createRequirementFromImportFile(Object requirementJson) { RequirementDefinition requirement = new RequirementDefinition(); @@ -546,11 +594,11 @@ public class ResourceImportManager { if (requirementJson instanceof String) { String requirementJsonString = (String) requirementJson; requirement.setCapability(requirementJsonString); - } - else if (requirementJson instanceof Map) { + } else if (requirementJson instanceof Map) { Map requirementJsonMap = (Map) requirementJson; if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())) { - requirement.setCapability((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())); + requirement.setCapability( + (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.CAPABILITY.getElementName())); } if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.NODE.getElementName())) { @@ -558,16 +606,17 @@ public class ResourceImportManager { } if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())) { - requirement.setRelationship((String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())); + requirement.setRelationship( + (String) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.RELATIONSHIP.getElementName())); } if (requirementJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List occurrencesList = (List) requirementJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); + List occurrencesList = (List) requirementJsonMap + .get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); validateOccurrences(occurrencesList); requirement.setMinOccurrences(occurrencesList.get(0).toString()); requirement.setMaxOccurrences(occurrencesList.get(1).toString()); } - } - else { + } else { throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML); } return requirement; @@ -576,7 +625,8 @@ public class ResourceImportManager { private void setProperties(Map toscaJson, Resource resource) { Map reducedToscaJson = new HashMap<>(toscaJson); ImportUtils.removeElementFromJsonMap(reducedToscaJson, "capabilities"); - Either, ResultStatusEnum> properties = ImportUtils.getProperties(reducedToscaJson); + Either, ResultStatusEnum> properties = ImportUtils + .getProperties(reducedToscaJson); if (properties.isLeft()) { List propertiesList = new ArrayList<>(); Map value = properties.left().value(); @@ -584,8 +634,11 @@ public class ResourceImportManager { for (Entry entry : value.entrySet()) { String name = entry.getKey(); if (!PROPERTY_NAME_PATTERN_IGNORE_LENGTH.matcher(name).matches()) { - log.debug("The property with invalid name {} occured upon import resource {}. ", name, resource.getName()); - throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, JsonPresentationFields.PROPERTY)); + log.debug("The property with invalid name {} occured upon import resource {}. ", name, + resource.getName()); + throw new ByActionStatusComponentException(componentsUtils + .convertFromResultStatusEnum(ResultStatusEnum.INVALID_PROPERTY_NAME, + JsonPresentationFields.PROPERTY)); } PropertyDefinition propertyDefinition = entry.getValue(); propertyDefinition.setName(name); @@ -593,44 +646,45 @@ public class ResourceImportManager { } } resource.setProperties(propertiesList); - } - else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) { + } else if (properties.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND) { throw new ByActionStatusComponentException(componentsUtils.convertFromResultStatusEnum(properties - .right() - .value(), JsonPresentationFields.PROPERTY)); + .right() + .value(), JsonPresentationFields.PROPERTY)); } } private ResultStatusEnum setAttributes(Map toscaJson, Resource resource) { ResultStatusEnum result = ResultStatusEnum.OK; - Either, ResultStatusEnum> attributes = ImportUtils.getAttributes(toscaJson); + Either, ResultStatusEnum> attributes = ImportUtils + .getAttributes(toscaJson); if (attributes.isLeft()) { - List attributeList = new ArrayList<>(); - Map value = attributes.left().value(); + List attributeList = new ArrayList<>(); + Map value = attributes.left().value(); if (value != null) { - for (Entry entry : value.entrySet()) { + for (Entry entry : value.entrySet()) { String name = entry.getKey(); - PropertyDefinition attributeDef = entry.getValue(); + AttributeDataDefinition attributeDef = entry.getValue(); attributeDef.setName(name); attributeList.add(attributeDef); } } resource.setAttributes(attributeList); - } - else { + } else { result = attributes.right().value(); } return result; } private Resource setDerivedFrom(Map toscaJson, Resource resource) { - Either toscaDerivedFromElement = ImportUtils.findFirstToscaStringElement(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM); + Either toscaDerivedFromElement = ImportUtils + .findFirstToscaStringElement(toscaJson, TypeUtils.ToscaTagNamesEnum.DERIVED_FROM); Resource derivedFromResource = null; if (toscaDerivedFromElement.isLeft()) { String derivedFrom = toscaDerivedFromElement.left().value(); log.debug("Derived from TOSCA name is {}", derivedFrom); resource.setDerivedFrom(Arrays.asList(new String[]{derivedFrom})); - Either latestByToscaResourceName = toscaOperationFacade.getLatestByToscaResourceName(derivedFrom); + Either latestByToscaResourceName = toscaOperationFacade + .getLatestByToscaResourceName(derivedFrom); if (latestByToscaResourceName.isRight()) { StorageOperationStatus operationStatus = latestByToscaResourceName.right().value(); @@ -640,7 +694,7 @@ public class ResourceImportManager { log.debug("Error when fetching parent resource {}, error: {}", derivedFrom, operationStatus); ActionStatus convertFromStorageResponse = componentsUtils.convertFromStorageResponse(operationStatus); BeEcompErrorManager.getInstance() - .logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom); + .logBeComponentMissingError("Import TOSCA YAML", "resource", derivedFrom); throw new ByActionStatusComponentException(convertFromStorageResponse, derivedFrom); } derivedFromResource = latestByToscaResourceName.left().value(); @@ -648,8 +702,10 @@ public class ResourceImportManager { return derivedFromResource; } - private void setCapabilities(Map toscaJson, Resource resource, Resource parentResource) {// Note that parentResource can be null - Either, ResultStatusEnum> toscaCapabilities = ImportUtils.findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES); + private void setCapabilities(Map toscaJson, Resource resource, + Resource parentResource) {// Note that parentResource can be null + Either, ResultStatusEnum> toscaCapabilities = ImportUtils + .findFirstToscaMapElement(toscaJson, TypeUtils.ToscaTagNamesEnum.CAPABILITIES); if (toscaCapabilities.isLeft()) { Map jsonCapabilities = toscaCapabilities.left().value(); Map> moduleCapabilities = new HashMap<>(); @@ -664,18 +720,20 @@ public class ResourceImportManager { // Validating that no req/cap duplicates exist in imported YAML String capNameLowerCase = capabilityNameValue.getKey().toLowerCase(); if (capNames.contains(capNameLowerCase)) { - log.debug("More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", capNameLowerCase); - throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", capNameLowerCase); + log.debug( + "More than one capability with same name {} (case-insensitive) in imported TOSCA file is invalid", + capNameLowerCase); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_DUPLICATE_REQ_CAP_NAME, "capability", + capNameLowerCase); } capNames.add(capNameLowerCase); CapabilityDefinition capabilityDef = createCapabilityFromImportFile(capabilityNameValue - .getValue()); + .getValue()); capabilityDef.setName(capabilityNameValue.getKey()); if (moduleCapabilities.containsKey(capabilityDef.getType())) { moduleCapabilities.get(capabilityDef.getType()).add(capabilityDef); - } - else { + } else { List list = new ArrayList<>(); list.add(capabilityDef); moduleCapabilities.put(capabilityDef.getType(), list); @@ -683,17 +741,19 @@ public class ResourceImportManager { // Validating against req/cap of "derived from" node Boolean validateVsParentCap = validateCapNameVsDerived(capName2TypeMap, capabilityDef - .getType(), capabilityDef.getName()); + .getType(), capabilityDef.getName()); if (!validateVsParentCap) { // Here parentResource is for sure not null, so it's // null-safe // Check added to avoid sonar warning String parentResourceName = parentResource != null ? parentResource.getName() : ""; - log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), parentResourceName); - throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, "capability", capabilityDef - .getName() - .toLowerCase(), parentResourceName); + log.debug("Capability with name {} already exists in parent {}", capabilityDef.getName(), + parentResourceName); + throw new ByActionStatusComponentException(ActionStatus.IMPORT_REQ_CAP_NAME_EXISTS_IN_DERIVED, + "capability", capabilityDef + .getName() + .toLowerCase(), parentResourceName); } } if (moduleCapabilities.size() > 0) { @@ -712,9 +772,12 @@ public class ResourceImportManager { String nameLowerCase = capDefinition.getName().toLowerCase(); if (capName2type.get(nameLowerCase) != null) { String parentResourceName = parentResource.getName(); - log.debug("Resource with name {} has more than one capability with name {}, ignoring case", parentResourceName, nameLowerCase); + log.debug("Resource with name {} has more than one capability with name {}, ignoring case", + parentResourceName, nameLowerCase); BeEcompErrorManager.getInstance() - .logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more capabilities with name " + nameLowerCase, ErrorSeverity.ERROR); + .logInternalDataError("Import resource", "Parent resource " + parentResourceName + + " of imported resource has one or more capabilities with name " + nameLowerCase, + ErrorSeverity.ERROR); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } capName2type.put(nameLowerCase, capDefinition.getType()); @@ -735,9 +798,12 @@ public class ResourceImportManager { String nameLowerCase = reqDefinition.getName().toLowerCase(); if (reqName2type.get(nameLowerCase) != null) { String parentResourceName = parentResource.getName(); - log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", parentResourceName, nameLowerCase); + log.debug("Resource with name {} has more than one requirement with name {}, ignoring case", + parentResourceName, nameLowerCase); BeEcompErrorManager.getInstance() - .logInternalDataError("Import resource", "Parent resource " + parentResourceName + " of imported resource has one or more requirements with name " + nameLowerCase, ErrorSeverity.ERROR); + .logInternalDataError("Import resource", "Parent resource " + parentResourceName + + " of imported resource has one or more requirements with name " + nameLowerCase, + ErrorSeverity.ERROR); throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } reqName2type.put(nameLowerCase, reqDefinition.getCapability()); @@ -748,19 +814,24 @@ public class ResourceImportManager { return reqName2type; } - private Boolean validateCapNameVsDerived(Map parentCapName2Type, String childCapabilityType, String reqCapName) { + private Boolean validateCapNameVsDerived(Map parentCapName2Type, String childCapabilityType, + String reqCapName) { String capNameLowerCase = reqCapName.toLowerCase(); log.trace("Validating capability {} vs parent resource", capNameLowerCase); String parentCapType = parentCapName2Type.get(capNameLowerCase); if (parentCapType != null) { if (childCapabilityType.equals(parentCapType)) { - log.debug("Capability with name {} is of same type {} for imported resource and its parent - this is OK", capNameLowerCase, childCapabilityType); + log.debug( + "Capability with name {} is of same type {} for imported resource and its parent - this is OK", + capNameLowerCase, childCapabilityType); return true; } - Either capabilityTypeDerivedFrom = capabilityTypeOperation.isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType); + Either capabilityTypeDerivedFrom = capabilityTypeOperation + .isCapabilityTypeDerivedFrom(childCapabilityType, parentCapType); if (capabilityTypeDerivedFrom.isRight()) { log.debug("Couldn't check whether imported resource capability derives from its parent's capability"); - throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom .right() .value())); } @@ -776,69 +847,73 @@ public class ResourceImportManager { if (capabilityJson instanceof String) { String capabilityJsonString = (String) capabilityJson; capabilityDefinition.setType(capabilityJsonString); - } - else if (capabilityJson instanceof Map) { + } else if (capabilityJson instanceof Map) { Map capabilityJsonMap = (Map) capabilityJson; // Type if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())) { - capabilityDefinition.setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())); + capabilityDefinition + .setType((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.TYPE.getElementName())); } // ValidSourceTypes if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { - capabilityDefinition.setValidSourceTypes((List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES + capabilityDefinition.setValidSourceTypes( + (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES .getElementName())); } // ValidSourceTypes if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())) { - capabilityDefinition.setDescription((String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())); + capabilityDefinition.setDescription( + (String) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())); } if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName())) { - List occurrencesList = (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); + List occurrencesList = (List) capabilityJsonMap + .get(TypeUtils.ToscaTagNamesEnum.OCCURRENCES.getElementName()); validateOccurrences(occurrencesList); capabilityDefinition.setMinOccurrences(occurrencesList.get(0).toString()); capabilityDefinition.setMaxOccurrences(occurrencesList.get(1).toString()); } if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.PROPERTIES.getElementName())) { - Either, ResultStatusEnum> propertiesRes = ImportUtils.getProperties(capabilityJsonMap); + Either, ResultStatusEnum> propertiesRes = ImportUtils + .getProperties(capabilityJsonMap); if (propertiesRes.isRight()) { throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND); - } - else { + } else { propertiesRes.left() - .value() - .entrySet() - .stream() - .forEach(e -> e.getValue().setName(e.getKey().toLowerCase())); + .value() + .entrySet() + .stream() + .forEach(e -> e.getValue().setName(e.getKey().toLowerCase())); List capabilityProperties = propertiesRes.left() - .value() - .values() - .stream() - .map(p -> new ComponentInstanceProperty(p, p - .getDefaultValue(), null)) - .collect(Collectors.toList()); + .value() + .values() + .stream() + .map(p -> new ComponentInstanceProperty(p, p + .getDefaultValue(), null)) + .collect(Collectors.toList()); capabilityDefinition.setProperties(capabilityProperties); } } - } - else if (!(capabilityJson instanceof List)) { + + } else if (!(capabilityJson instanceof List)) { throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML); } return capabilityDefinition; } - private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, RuntimeException e) { + private void handleImportResourceException(UploadResourceInfo resourceMetaData, User user, boolean isNormative, + RuntimeException e) { ResponseFormat responseFormat; ComponentException newException; if (e instanceof ComponentException) { - ComponentException componentException = (ComponentException)e; + ComponentException componentException = (ComponentException) e; responseFormat = componentException.getResponseFormat(); if (responseFormat == null) { - responseFormat = getResponseFormatManager().getResponseFormat(componentException.getActionStatus(), componentException.getParams()); + responseFormat = getResponseFormatManager() + .getResponseFormat(componentException.getActionStatus(), componentException.getParams()); } newException = componentException; - } - else{ + } else { responseFormat = getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR); newException = new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } @@ -849,13 +924,13 @@ public class ResourceImportManager { throw newException; } - private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, boolean isNormative) { + private void auditErrorImport(UploadResourceInfo resourceMetaData, User user, ResponseFormat errorResponseWrapper, + boolean isNormative) { String version, lifeCycleState; if (isNormative) { version = TypeUtils.getFirstCertifiedVersionVersion(); lifeCycleState = LifecycleStateEnum.CERTIFIED.name(); - } - else { + } else { version = ""; lifeCycleState = LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name(); @@ -867,23 +942,22 @@ public class ResourceImportManager { } message += errorResponseWrapper.getFormattedMessage(); - AuditEventFactory factory = new AuditImportResourceAdminEventFactory( - CommonAuditData.newBuilder() - .status(errorResponseWrapper.getStatus()) - .description(message) - .requestId(ThreadLocalsHolder.getUuid()) - .build(), - new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()), - ResourceVersionInfo.newBuilder() - .state(lifeCycleState) - .version(version) - .build(), - ResourceVersionInfo.newBuilder() - .state("") - .version("") - .build(), - "", user, ""); + CommonAuditData.newBuilder() + .status(errorResponseWrapper.getStatus()) + .description(message) + .requestId(ThreadLocalsHolder.getUuid()) + .build(), + new ResourceCommonInfo(resourceMetaData.getName(), ComponentTypeEnum.RESOURCE.getValue()), + ResourceVersionInfo.newBuilder() + .state(lifeCycleState) + .version(version) + .build(), + ResourceVersionInfo.newBuilder() + .state("") + .version("") + .build(), + "", user, ""); getAuditingManager().auditEvent(factory); } @@ -895,15 +969,58 @@ public class ResourceImportManager { final String payloadData = resourceMetaData.getPayloadData(); if (payloadData != null) { resource.setToscaVersion(getToscaVersion(payloadData)); + resource.setAttributes(getAttributes(payloadData)); } final List categories = resourceMetaData.getCategories(); calculateResourceIsAbstract(resource, categories); } - private String getToscaVersion(final String payloadData) { + private List getAttributes(final String payloadData) { + final Map mappedToscaTemplate = decodePayload(payloadData); + + final List attributeDataDefinitionList = new ArrayList<>(); + + final Either, ResultStatusEnum> firstToscaMapElement = ImportUtils + .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.ATTRIBUTES); + if (firstToscaMapElement.isRight()) { + return attributeDataDefinitionList; + } + final Map attributes = firstToscaMapElement.left().value(); + + final Iterator> propertiesNameValue = attributes.entrySet().iterator(); + while (propertiesNameValue.hasNext()) { + final Entry attributeNameValue = propertiesNameValue.next(); + final Object value = attributeNameValue.getValue(); + final String key = attributeNameValue.getKey(); + if (value instanceof Map) { + + final Map attributeMap = (Map) value; + + final AttributeDefinition attributeDefinition = new AttributeDefinition(); + attributeDefinition.setName(key); + + setField(attributeMap, ToscaTagNamesEnum.DESCRIPTION, attributeDefinition::setDescription); + setField(attributeMap, ToscaTagNamesEnum.TYPE, attributeDefinition::setType); + setField(attributeMap, ToscaTagNamesEnum.STATUS, attributeDefinition::setStatus); + setField(attributeMap, ToscaTagNamesEnum.ENTRY_SCHEMA, attributeDefinition::setEntry_schema); + attributeDataDefinitionList.add(attributeDefinition); + } else { + final AttributeDefinition attributeDefinition = new AttributeDefinition(); + attributeDefinition.setName(key); + attributeDataDefinitionList.add(attributeDefinition); + } + } + return attributeDataDefinitionList; + } + + private Map decodePayload(final String payloadData) { final String decodedPayload = new String(Base64.decodeBase64(payloadData)); - final Map mappedToscaTemplate = (Map) new Yaml().load(decodedPayload); + return (Map) new Yaml().load(decodedPayload); + } + + private String getToscaVersion(final String payloadData) { + final Map mappedToscaTemplate = decodePayload(payloadData); final Either findFirstToscaStringElement = ImportUtils.findFirstToscaStringElement(mappedToscaTemplate, TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); return findFirstToscaStringElement.left().value(); @@ -914,7 +1031,7 @@ public class ResourceImportManager { CategoryDefinition categoryDef = categories.get(0); resource.setAbstract(false); if (categoryDef != null && categoryDef.getName() != null && categoryDef.getName() - .equals(Constants.ABSTRACT_CATEGORY_NAME)) { + .equals(Constants.ABSTRACT_CATEGORY_NAME)) { SubCategoryDefinition subCategoryDef = categoryDef.getSubcategories().get(0); if (subCategoryDef != null && subCategoryDef.getName().equals(Constants.ABSTRACT_SUBCATEGORY)) { resource.setAbstract(true); @@ -929,8 +1046,7 @@ public class ResourceImportManager { if (shouldBeCertified) { version = TypeUtils.getFirstCertifiedVersionVersion(); state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE; - } - else { + } else { version = ImportUtils.Constants.FIRST_NON_CERTIFIED_VERSION; state = ImportUtils.Constants.NORMATIVE_TYPE_LIFE_CYCLE_NOT_CERTIFIED_CHECKOUT; } @@ -959,8 +1075,7 @@ public class ResourceImportManager { Integer maxOccurrences; if (minObj instanceof Integer) { minOccurrences = (Integer) minObj; - } - else { + } else { log.debug("Invalid occurrenses format. low_bound occurrense must be Integer {}", minObj); throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } @@ -969,23 +1084,22 @@ public class ResourceImportManager { throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } - if (maxObj instanceof String){ - if(!"UNBOUNDED".equals(maxObj)) { + if (maxObj instanceof String) { + if (!"UNBOUNDED".equals(maxObj)) { log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } - } - else { + } else { if (maxObj instanceof Integer) { maxOccurrences = (Integer) maxObj; - } - else { + } else { log.debug("Invalid occurrenses format. Max occurrence is {}", maxObj); throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } if (maxOccurrences <= 0 || maxOccurrences < minOccurrences) { - log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, maxOccurrences); + log.debug("Invalid occurrenses format. min occurrence is {}, Max occurrence is {}", minOccurrences, + maxOccurrences); throw new ByActionStatusComponentException(ActionStatus.INVALID_OCCURRENCES); } } @@ -1004,7 +1118,8 @@ public class ResourceImportManager { } private ResourceBusinessLogic getResourceBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context + .getAttribute(org.openecomp.sdc.common.api.Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); return webApplicationContext.getBean(ResourceBusinessLogic.class); } @@ -1033,7 +1148,7 @@ public class ResourceImportManager { public void setResourceBusinessLogic(ResourceBusinessLogic resourceBusinessLogic) { this.resourceBusinessLogic = resourceBusinessLogic; } - + @Autowired public void setInterfaceOperationBusinessLogic(InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) { this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java index 3050128531..9f54f1fae8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AttributeServlet.java @@ -31,9 +31,7 @@ import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.servers.Server; -import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.tags.Tags; import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; @@ -41,9 +39,10 @@ import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; -import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; @@ -76,8 +75,8 @@ import java.io.IOException; */ @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") -@Tags({@Tag(name = "SDC Internal APIs")}) -@Servers({@Server(url = "/sdc2/rest")}) +@Tag(name = "SDC Internal APIs") +@Server(url = "/sdc2/rest") @Controller public class AttributeServlet extends AbstractValidationsServlet { private static final Logger log = Logger.getLogger(AttributeServlet.class); @@ -124,13 +123,13 @@ public class AttributeServlet extends AbstractValidationsServlet { try { Wrapper errorWrapper = new Wrapper<>(); - Wrapper attributesWrapper = new Wrapper<>(); + Wrapper attributesWrapper = new Wrapper<>(); // convert json to AttributeDefinition buildAttributeFromString(data, attributesWrapper, errorWrapper); if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); + Either createAttribute = businessLogic.createAttribute(resourceId, attributesWrapper.getInnerElement(), userId); if (createAttribute.isRight()) { errorWrapper.setInnerElement(createAttribute.right().value()); } else { @@ -143,7 +142,7 @@ public class AttributeServlet extends AbstractValidationsServlet { log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement()); response = buildErrorResponse(errorWrapper.getInnerElement()); } else { - PropertyDefinition createdAttDef = attributesWrapper.getInnerElement(); + AttributeDataDefinition createdAttDef = attributesWrapper.getInnerElement(); log.debug("Attribute {} created successfully with id {}", createdAttDef.getName(), createdAttDef.getUniqueId()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(createdAttDef)); @@ -200,14 +199,14 @@ public class AttributeServlet extends AbstractValidationsServlet { try { // convert json to PropertyDefinition Wrapper errorWrapper = new Wrapper<>(); - Wrapper attributesWrapper = new Wrapper<>(); + Wrapper attributesWrapper = new Wrapper<>(); // convert json to AttributeDefinition buildAttributeFromString(data, attributesWrapper, errorWrapper); if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); + Either eitherUpdateAttribute = businessLogic.updateAttribute(resourceId, attributeId, attributesWrapper.getInnerElement(), userId); // update property if (eitherUpdateAttribute.isRight()) { errorWrapper.setInnerElement(eitherUpdateAttribute.right().value()); @@ -221,7 +220,7 @@ public class AttributeServlet extends AbstractValidationsServlet { log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement()); response = buildErrorResponse(errorWrapper.getInnerElement()); } else { - PropertyDefinition updatedAttribute = attributesWrapper.getInnerElement(); + AttributeDataDefinition updatedAttribute = attributesWrapper.getInnerElement(); log.debug("Attribute id {} updated successfully ", updatedAttribute.getUniqueId()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(updatedAttribute)); @@ -271,15 +270,14 @@ public class AttributeServlet extends AbstractValidationsServlet { log.debug("modifier id is {}", userId); try { - // delete the property AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); + Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); if (eitherAttribute.isRight()) { log.debug("Failed to delete Attribute. Reason - ", eitherAttribute.right().value()); return buildErrorResponse(eitherAttribute.right().value()); } - PropertyDefinition attributeDefinition = eitherAttribute.left().value(); + AttributeDataDefinition attributeDefinition = eitherAttribute.left().value(); String name = attributeDefinition.getName(); log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId()); @@ -293,11 +291,11 @@ public class AttributeServlet extends AbstractValidationsServlet { } } - private void buildAttributeFromString(String data, Wrapper attributesWrapper, + private void buildAttributeFromString(String data, Wrapper attributesWrapper, Wrapper errorWrapper) { try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); - final PropertyDefinition attribute = gson.fromJson(data, PropertyDefinition.class); + final AttributeDataDefinition attribute = gson.fromJson(data, AttributeDefinition.class); if (attribute == null) { log.info(ATTRIBUTE_CONTENT_IS_INVALID, data); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index 13a90a822f..518ed5726c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -54,6 +54,7 @@ import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundExcept import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; @@ -1060,6 +1061,14 @@ public class ToscaExportHandler { : NATIVE_ROOT; toscaNodeType.setDerived_from(derivedFrom); } + if (component instanceof Resource) { + final List attributes = ((Resource) component).getAttributes(); + if (CollectionUtils.isNotEmpty(attributes)) { + final Map attributeDataDefinitionMap + = attributes.stream().collect(Collectors.toMap(AttributeDataDefinition::getName, a -> a)); + toscaNodeType.setAttributes(attributeDataDefinitionMap); + } + } return toscaNodeType; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java index b7fe3bc13a..04515b297c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeTemplate.java @@ -21,6 +21,7 @@ package org.openecomp.sdc.be.tosca.model; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; @@ -31,6 +32,7 @@ import java.util.Map; @Getter @Setter +@NoArgsConstructor public class ToscaNodeTemplate { private String type; @@ -45,11 +47,7 @@ public class ToscaNodeTemplate { private Map interfaces; public void setDirectives(List directives) { - if (CollectionUtils.isEmpty(directives)) { - this.directives = null; - return; - } - this.directives = directives; + this.directives = CollectionUtils.isEmpty(directives) ? null : directives; } public void addInterface(String interfaceName, Object interfaceDataDefinition) { @@ -60,4 +58,3 @@ public class ToscaNodeTemplate { this.interfaces.put(interfaceName, interfaceDataDefinition); } } - diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java index 0d0cfb27b7..b5e5866fe4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/model/ToscaNodeType.java @@ -22,75 +22,25 @@ package org.openecomp.sdc.be.tosca.model; import java.util.List; import java.util.Map; - +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; + +@Getter +@Setter +@NoArgsConstructor public class ToscaNodeType { - public ToscaNodeType() { - } - private ToscaMetadata metadata; private String derived_from; private String description; private Map properties; - private Map interfaces; //ToscaInterfaceDefinition + private Map interfaces; private Map capabilities; private List> requirements; + private Map attributes; - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } - - public Map getCapabilities() { - return capabilities; - } - - public void setCapabilities(Map capabilities) { - this.capabilities = capabilities; - } - - public List> getRequirements() { - return requirements; - } - - public void setRequirements(List> requirements) { - this.requirements = requirements; - } - - public String getDerived_from() { - return derived_from; - } - - public void setDerived_from(String derived_from) { - this.derived_from = derived_from; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public ToscaMetadata getMetadata() { - return metadata; - } - - public void setMetadata(ToscaMetadata metadata) { - this.metadata = metadata; - } - - public Map getInterfaces() { - return interfaces; - } - - public void setInterfaces(Map interfaces) { - this.interfaces = interfaces; - } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java index 57af76a103..db4c699d04 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogicTest.java @@ -31,9 +31,10 @@ import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; @@ -53,6 +54,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.Mockito.when; +import org.openecomp.sdc.be.model.DataTypeDefinition; public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ @@ -74,7 +76,6 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ AttributeBusinessLogic attributeBusinessLogic=createTestSubject(); IGraphLockOperation igraphLockOperation = Mockito.mock(IGraphLockOperation.class); - @Before public void setup() throws Exception{ @@ -107,23 +108,21 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ baseBusinessLogic.set(attributeBusinessLogic, propertyOperation); } - @Test public void testCreateAttribute() throws Exception { AttributeBusinessLogic testSubject; String resourceId = ""; PropertyDefinition newAttributeDef = null; String userId = ""; - Either result; + Either result; // default test testSubject = createTestSubject(); } - @Test public void testIsAttributeExist() throws Exception { - AttributeBusinessLogic testSubject;List attributes = null; + AttributeBusinessLogic testSubject;List attributes = null; String resourceUid = ""; String propertyName = ""; boolean result; @@ -132,7 +131,6 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ testSubject=createTestSubject();attributes = null; } - @Test public void testGetAttribute() throws Exception { AttributeBusinessLogic testSubject; @@ -145,7 +143,6 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ testSubject = createTestSubject(); } - @Test public void testUpdateAttribute() throws Exception { AttributeBusinessLogic testSubject; @@ -159,7 +156,6 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ testSubject = createTestSubject(); } - @Test public void testDeleteAttribute() throws Exception { AttributeBusinessLogic testSubject; @@ -172,11 +168,10 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ testSubject = createTestSubject(); } - @Test public void createAttribute_lockfail() throws Exception { - Either response; - PropertyDefinition prop= new PropertyDefinition(); + Either response; + AttributeDataDefinition prop= new AttributeDataDefinition(); response = attributeBusinessLogic.createAttribute("RES01", prop, "USR01"); @@ -187,36 +182,36 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ @Test public void createAttribute_Success() throws Exception { - Component resource= new Resource(); + Component resource = new Resource(); resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); resource.setIsDeleted(false); resource.setLastUpdaterUserId("USR01"); - PropertyDefinition prop= new PropertyDefinition(); - prop.setType(ToscaPropertyType.STRING.getType()); + AttributeDefinition attrib = new AttributeDefinition(); + attrib.setType(ToscaPropertyType.STRING.getType()); - when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); //Either toscastatus=Either.right(StorageOperationStatus.INVALID_PROPERTY); - Either toscastatus=Either.left(resource); + Either toscastatus = Either.left(resource); when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - PropertyDefinition propertyDefinition = new PropertyDefinition(); - Either either = Either.left(propertyDefinition); - when(toscaOperationFacade.addAttributeOfResource(anyObject(),anyObject())).thenReturn(either); + AttributeDataDefinition attributeDataDefinition = new AttributeDataDefinition(); + Either either = Either.left(attributeDataDefinition); + when(toscaOperationFacade.addAttributeOfResource(anyObject(), anyObject())).thenReturn(either); when(propertyOperation.isPropertyTypeValid(anyObject())).thenReturn(true); - Map data=new HashMap<>(); - data.put("ONE",new DataTypeDefinition()); + Map data = new HashMap<>(); + data.put("ONE", new DataTypeDefinition()); Either, JanusGraphOperationStatus> allDataTypes = Either.left(data); when(applicationDataTypeCache.getAll()).thenReturn(allDataTypes); - when(propertyOperation.isPropertyDefaultValueValid(anyObject(),anyObject())).thenReturn(true); - Either response; + when(propertyOperation.isPropertyDefaultValueValid(anyObject(), anyObject())).thenReturn(true); + Either response; - response = attributeBusinessLogic.createAttribute("RES01", prop, "USR01"); + response = attributeBusinessLogic.createAttribute("RES01", attrib, "USR01"); - Assert.assertEquals(true,response.isLeft()); + Assert.assertEquals(true, response.isLeft()); } @@ -230,8 +225,8 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); - Either response; - PropertyDefinition prop= new PropertyDefinition(); + Either response; + AttributeDataDefinition prop= new AttributeDataDefinition(); baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("toscaOperationFacade"); baseBusinessLogic.setAccessible(true); @@ -256,8 +251,8 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); - Either response; - PropertyDefinition prop= new PropertyDefinition(); + Either response; + AttributeDataDefinition prop= new AttributeDataDefinition(); //Either toscastatus=Either.right(StorageOperationStatus.INVALID_PROPERTY); Either toscastatus=Either.left(resource); @@ -272,73 +267,71 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ @Test public void createAttribute_componentalreadyexist_fails() throws Exception { - Either response; - PropertyDefinition prop= new PropertyDefinition(); - prop.setName("RES01"); - prop.setParentUniqueId("RES01"); + Either response; + AttributeDefinition attrib = new AttributeDefinition(); + attrib.setName("RES01"); + attrib.setParentUniqueId("RES01"); - List attributes = new ArrayList<>(); - attributes.add(prop); + List attributes = new ArrayList<>(); + attributes.add(attrib); - Component resource= new Resource(); + Component resource = new Resource(); resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); resource.setIsDeleted(false); resource.setLastUpdaterUserId("USR01"); ((Resource) resource).setAttributes(attributes); - when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); //Either toscastatus=Either.right(StorageOperationStatus.INVALID_PROPERTY); - Either toscastatus=Either.left(resource); + Either toscastatus = Either.left(resource); when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - response = attributeBusinessLogic.createAttribute("RES01", prop, "USR01"); + response = attributeBusinessLogic.createAttribute("RES01", attrib, "USR01"); - Assert.assertEquals(true,response.isRight()); + Assert.assertEquals(true, response.isRight()); } - @Test public void createAttribute_addresourcetostoragefails() throws Exception { - Component resource= new Resource(); + Component resource = new Resource(); resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); resource.setIsDeleted(false); resource.setLastUpdaterUserId("USR01"); - PropertyDefinition prop= new PropertyDefinition(); - prop.setType(ToscaPropertyType.STRING.getType()); - IGraphLockOperation igraphLockOperation = Mockito.mock(IGraphLockOperation.class); - when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); //Either toscastatus=Either.right(StorageOperationStatus.INVALID_PROPERTY); - Either toscastatus=Either.left(resource); + Either toscastatus = Either.left(resource); when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - PropertyDefinition propertyDefinition = new PropertyDefinition(); - Either either = Either.right(StorageOperationStatus.CONNECTION_FAILURE); - when(toscaOperationFacade.addAttributeOfResource(anyObject(),anyObject())).thenReturn(either); + AttributeDataDefinition attributeDataDefinition = new AttributeDataDefinition(); + Either either = Either + .right(StorageOperationStatus.CONNECTION_FAILURE); + when(toscaOperationFacade.addAttributeOfResource(anyObject(), anyObject())).thenReturn(either); when(propertyOperation.isPropertyTypeValid(anyObject())).thenReturn(true); - Map data=new HashMap<>(); - data.put("ONE",new DataTypeDefinition()); + Map data = new HashMap<>(); + data.put("ONE", new DataTypeDefinition()); Either, JanusGraphOperationStatus> allDataTypes = Either.left(data); when(applicationDataTypeCache.getAll()).thenReturn(allDataTypes); - when(propertyOperation.isPropertyDefaultValueValid(anyObject(),anyObject())).thenReturn(true); - Either response; + when(propertyOperation.isPropertyDefaultValueValid(anyObject(), anyObject())).thenReturn(true); + Either response; - response = attributeBusinessLogic.createAttribute("RES01", prop, "USR01"); + AttributeDataDefinition attrib = new AttributeDefinition(); + response = attributeBusinessLogic.createAttribute("RES01", attrib, "USR01"); - Assert.assertEquals(true,response.isRight()); + Assert.assertEquals(true, response.isRight()); } @Test public void testgetAttribute_ATTRIBUTE_NOT_FOUND() throws Exception { - Either result; + Either result; Component resource= new Resource(); resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); @@ -353,31 +346,31 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ @Test public void testgetAttribute_success() throws Exception { - Either result; + Either result; - Component resource= new Resource(); + Component resource = new Resource(); resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); resource.setIsDeleted(false); resource.setLastUpdaterUserId("USR01"); - PropertyDefinition prop= new PropertyDefinition(); - prop.setUniqueId("ATTR01"); - prop.setParentUniqueId("RES01"); + AttributeDefinition attrib = new AttributeDefinition(); + attrib.setUniqueId("ATTR01"); + attrib.setParentUniqueId("RES01"); - List attr = new ArrayList<>(); - attr.add(prop); + List attr = new ArrayList<>(); + attr.add(attrib); ((Resource) resource).setAttributes(attr); - Either toscastatus=Either.left(resource); + Either toscastatus = Either.left(resource); when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - result=attributeBusinessLogic.getAttribute("RES01","ATTR01", "USR01"); - Assert.assertEquals(true,result.isLeft()); + result = attributeBusinessLogic.getAttribute("RES01", "ATTR01", "USR01"); + Assert.assertEquals(true, result.isLeft()); } @Test public void testgetAttribute_RESOURCE_NOT_FOUND() throws Exception { - Either result; + Either result; Either toscastatus=Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); @@ -388,7 +381,7 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ @Test public void testdeleteAttribute_FAILED_TO_LOCK_COMPONENT() throws Exception { - Either result; + Either result; result=attributeBusinessLogic.deleteAttribute("RES01","ATTR01", "USR01"); Assert.assertEquals(true,result.isRight()); @@ -396,7 +389,7 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ @Test public void testdeleteAttribute_get_RESOURCE_from_DB_failed() throws Exception { - Either result; + Either result; Either toscastatus=Either.right(StorageOperationStatus.CONNECTION_FAILURE); when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); @@ -407,7 +400,7 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ @Test public void testdeleteAttribute_get_RESOURCE_verification_failed() throws Exception { - Either result; + Either result; Component resource= new Resource(); @@ -430,7 +423,7 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ @Test public void testdeleteAttribute_nonexistingresource() throws Exception { - Either result; + Either result; Component resource= new Resource(); @@ -449,7 +442,7 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ @Test public void testdeleteAttribute_success() throws Exception { - Either result; + Either result; Component resource= new Resource(); @@ -457,23 +450,21 @@ public class AttributeBusinessLogicTest extends BaseBusinessLogicMock{ resource.setIsDeleted(false); resource.setLastUpdaterUserId("USR01"); + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); - when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); - - Either toscastatus=Either.left(resource); + Either toscastatus = Either.left(resource); when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - when(toscaOperationFacade.deleteAttributeOfResource(any(),any())).thenReturn(StorageOperationStatus.OK); + when(toscaOperationFacade.deleteAttributeOfResource(any(), any())).thenReturn(StorageOperationStatus.OK); - PropertyDefinition prop= new PropertyDefinition(); - prop.setUniqueId("ATTR01"); - prop.setParentUniqueId("RES01"); - List attributes = new ArrayList<>(); - attributes.add(prop); + AttributeDefinition attrib = new AttributeDefinition(); + attrib.setUniqueId("ATTR01"); + attrib.setParentUniqueId("RES01"); + List attributes = new ArrayList<>(); + attributes.add(attrib); ((Resource) resource).setAttributes(attributes); - result=attributeBusinessLogic.deleteAttribute("RES01","ATTR01", "USR01"); - Assert.assertEquals(true,result.isLeft()); + result = attributeBusinessLogic.deleteAttribute("RES01", "ATTR01", "USR01"); + Assert.assertEquals(true, result.isLeft()); } - -} \ No newline at end of file +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java index 127e1d9aba..f213835406 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ComponentInstanceBusinessLogicTest.java @@ -22,9 +22,12 @@ package org.openecomp.sdc.be.components.impl; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.DynamicTest.dynamicTest; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anySet; @@ -57,6 +60,8 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; @@ -88,6 +93,7 @@ import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentInstanceAttribute; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.InputDefinition; @@ -120,6 +126,7 @@ import org.openecomp.sdc.exception.ResponseFormat; */ @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) class ComponentInstanceBusinessLogicTest { private final static String USER_ID = "jh0003"; @@ -486,8 +493,7 @@ class ComponentInstanceBusinessLogicTest { ComponentInstance responseFormatEither = componentInstanceBusinessLogic .deleteForwardingPathsRelatedTobeDeletedComponentInstance( containerComponentID, containerComponentType, ci); - assertThat(!responseFormatEither.isEmpty()).isEqualTo(true); - + assertFalse(responseFormatEither.isEmpty()); } @Test @@ -624,7 +630,7 @@ class ComponentInstanceBusinessLogicTest { componentInstanceBusinessLogic .getRelationById(COMPONENT_ID, RELATION_ID, USER_ID, component.getComponentType()); } catch (ByActionStatusComponentException e) { - assertSame(e.getActionStatus(), ActionStatus.USER_NOT_FOUND); + assertSame(ActionStatus.USER_NOT_FOUND, e.getActionStatus()); } } @@ -887,7 +893,7 @@ class ComponentInstanceBusinessLogicTest { // default test testSubject = createTestSubject(); result = Deencapsulation.invoke(testSubject, "validateParent", new Object[]{resource, nodeTemplateId}); - assertNotNull(result); + assertFalse(result); } @Test @@ -940,6 +946,7 @@ class ComponentInstanceBusinessLogicTest { testSubject = createTestSubject(); result = Deencapsulation.invoke(testSubject, "findRelation", new Object[]{relationId, requirementCapabilityRelations}); + assertNull(result); } @Test @@ -990,6 +997,7 @@ class ComponentInstanceBusinessLogicTest { testSubject = createTestSubject(); result = Deencapsulation.invoke(testSubject, "updateCapabilityPropertyOnContainerComponent", new Object[]{property, newValue, resource, toInstance, capabilityType, capabilityName}); + assertNull(result); } @Test @@ -1224,7 +1232,7 @@ class ComponentInstanceBusinessLogicTest { @Test void testCreateOrUpdateAttributeValueForCopyPaste() { ComponentInstance serviceComponentInstance = createComponetInstanceFromComponent(service); - ComponentInstanceProperty attribute = new ComponentInstanceProperty(); + ComponentInstanceAttribute attribute = new ComponentInstanceAttribute(); attribute.setType("string"); attribute.setUniqueId("testCreateOrUpdateAttributeValueForCopyPaste"); SchemaDefinition def = Mockito.mock(SchemaDefinition.class); @@ -1234,9 +1242,9 @@ class ComponentInstanceBusinessLogicTest { service.setLastUpdaterUserId(USER_ID); service.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - Map> instAttrsMap = new HashMap<>(); - List instAttrsList = new ArrayList<>(); - ComponentInstanceProperty prop = new ComponentInstanceProperty(); + Map> instAttrsMap = new HashMap<>(); + List instAttrsList = new ArrayList<>(); + ComponentInstanceAttribute prop = new ComponentInstanceAttribute(); prop.setUniqueId(attribute.getUniqueId()); instAttrsList.add(prop); instAttrsMap.put(toInstance.getUniqueId(), instAttrsList); @@ -1250,7 +1258,7 @@ class ComponentInstanceBusinessLogicTest { when(toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(service)) .thenReturn(serviceEitherLeft); - Either result = Deencapsulation + Either result = Deencapsulation .invoke(componentInstanceBusinessLogic, "createOrUpdateAttributeValueForCopyPaste", ComponentTypeEnum.SERVICE, @@ -1264,8 +1272,8 @@ class ComponentInstanceBusinessLogicTest { service.setLifecycleState(oldLifeCycleState); assertThat(result.isLeft()).isTrue(); - ComponentInstanceProperty resultProp = result.left().value(); - assertEquals(resultProp.getPath().size(), 1); + ComponentInstanceAttribute resultProp = result.left().value(); + assertEquals(1, resultProp.getPath().size()); assertEquals(resultProp.getPath().get(0), toInstance.getUniqueId()); } @@ -1496,8 +1504,8 @@ class ComponentInstanceBusinessLogicTest { Optional propertyCandidate = getComponentInstanceProperty(PROP_NAME); - assertThat(propertyCandidate.isPresent()).isTrue(); - assertEquals(propertyCandidate.get().getName(), PROP_NAME); + assertThat(propertyCandidate).isPresent(); + assertEquals(PROP_NAME, propertyCandidate.get().getName()); } @Test diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java index e47cdc999e..3783c5e1fd 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ImportUtilsTest.java @@ -28,10 +28,12 @@ import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum; import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaElementTypeEnum; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; +import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.HeatParameterDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.model.operations.impl.AnnotationTypeOperations; import org.openecomp.sdc.be.model.tosca.constraints.ValidValuesConstraint; import org.openecomp.sdc.be.utils.TypeUtils; @@ -305,7 +307,7 @@ public class ImportUtilsTest { public void testGetAttributesFromYml() throws IOException { Map toscaJson = (Map) loadJsonFromFile("importToscaWithAttribute.yml"); - Either, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); + Either, ResultStatusEnum> actualAttributes = ImportUtils.getAttributes(toscaJson); assertTrue(actualAttributes.isLeft()); Map> expectedAttributes = getElements(toscaJson, TypeUtils.ToscaTagNamesEnum.ATTRIBUTES); compareAttributes(expectedAttributes, actualAttributes.left().value()); @@ -364,10 +366,10 @@ public class ImportUtilsTest { } - private void compareAttributes(Map> expected, Map actual) { + private void compareAttributes(Map> expected, Map actual) { Map singleExpectedAttribute; - PropertyDefinition actualAttribute, expectedAttributeModel; + AttributeDataDefinition actualAttribute, expectedAttributeModel; // attributes of resource for (Map.Entry> expectedAttribute : expected.entrySet()) { @@ -379,11 +381,11 @@ public class ImportUtilsTest { expectedAttributeModel = ImportUtils.createModuleAttribute(singleExpectedAttribute); expectedAttributeModel.setName(expectedAttribute.getKey().toString()); - assertEquals(expectedAttributeModel.getDefaultValue(), actualAttribute.getDefaultValue()); - assertEquals(expectedAttributeModel.getDescription(), actualAttribute.getDescription()); - assertEquals(expectedAttributeModel.getName(), actualAttribute.getName()); - assertEquals(expectedAttributeModel.getStatus(), actualAttribute.getStatus()); - assertEquals(expectedAttributeModel.getType(), actualAttribute.getType()); + assertEquals(((AttributeDefinition)expectedAttributeModel).getDefaultValue(), ((AttributeDefinition)actualAttribute).getDefaultValue()); + assertEquals(((AttributeDefinition)expectedAttributeModel).getDescription(), ((AttributeDefinition)actualAttribute).getDescription()); + assertEquals(((AttributeDefinition)expectedAttributeModel).getName(), ((AttributeDefinition)actualAttribute).getName()); + assertEquals(((AttributeDefinition)expectedAttributeModel).getStatus(), ((AttributeDefinition)actualAttribute).getStatus()); + assertEquals(((AttributeDefinition)expectedAttributeModel).getType(), ((AttributeDefinition)actualAttribute).getType()); compareSchemas(expectedAttributeModel.getSchema(), actualAttribute.getSchema()); -- cgit 1.2.3-korg