From fee0f29212b10c940ec4b19fc8f4794d06964eee Mon Sep 17 00:00:00 2001 From: vasraz Date: Thu, 18 Feb 2021 13:13:50 +0000 Subject: Implement Attributes/Outputs BE (part 1) This commit includes support for: - import VFC with attributes - add VFC to VF/Service - show attributes in VF/Service Change-Id: I2cda966ab878ae7aee4bcfecf266c5c251c91164 Signed-off-by: Vasyl Razinkov Issue-ID: SDC-3448 Signed-off-by: JulienBe --- .../tasks/mig1806/ForwardPathMigration.java | 2 +- .../be/components/impl/AttributeBusinessLogic.java | 147 ++- .../be/components/impl/ComponentBusinessLogic.java | 8 +- .../impl/ComponentInstanceBusinessLogic.java | 80 +- .../be/components/impl/OutputsBusinessLogic.java | 102 ++ .../be/components/impl/ResourceBusinessLogic.java | 9 +- .../be/components/impl/ResourceImportManager.java | 19 +- .../impl/ServiceImportBusinessLogic.java | 1165 +++++++++++--------- .../components/impl/ServiceImportParseLogic.java | 4 +- .../ComponentInstanceMergeDataBusinessLogic.java | 2 +- .../components/path/ForwardingPathValidator.java | 2 +- .../datamodel/utils/UiComponentDataConverter.java | 13 +- .../sdc/be/servlets/AttributeServlet.java | 124 +-- .../sdc/be/servlets/ComponentAttributeServlet.java | 142 +++ .../sdc/be/servlets/ComponentInstanceServlet.java | 29 +- .../openecomp/sdc/be/servlets/OutputsServlet.java | 119 ++ .../openecomp/sdc/be/tosca/ToscaExportHandler.java | 48 +- .../impl/AttributeBusinessLogicTest.java | 571 +++++----- .../impl/ServiceImportBusinessLogicTest.java | 11 +- .../impl/ServiceImportParseLogicTest.java | 174 ++- .../sdc/be/dao/jsongraph/types/VertexTypeEnum.java | 3 +- .../sdc/be/model/AttributeDefinition.java | 6 +- .../java/org/openecomp/sdc/be/model/Component.java | 34 +- .../openecomp/sdc/be/model/ComponentInstance.java | 2 +- .../sdc/be/model/ComponentInstanceAttribute.java | 3 +- .../sdc/be/model/ComponentInstanceOutput.java | 73 ++ .../sdc/be/model/ComponentParametersView.java | 250 +---- .../sdc/be/model/IAttributeInputCommon.java | 33 - .../sdc/be/model/IAttributeOutputCommon.java | 33 + .../openecomp/sdc/be/model/OutputDefinition.java | 8 +- .../java/org/openecomp/sdc/be/model/Resource.java | 55 +- .../model/jsonjanusgraph/datamodel/NodeType.java | 2 - .../jsonjanusgraph/datamodel/ToscaElement.java | 6 +- .../operations/NodeTypeOperation.java | 2 +- .../operations/TopologyTemplateOperation.java | 23 +- .../operations/ToscaElementOperation.java | 2 +- .../operations/ToscaOperationFacade.java | 71 +- .../model/jsonjanusgraph/utils/ModelConverter.java | 1055 +++++++++--------- .../sdc/be/ui/model/UiComponentDataTransfer.java | 2 + .../sdc/be/ui/model/UiResourceDataTransfer.java | 3 +- .../sdc/be/model/ComponentParametersViewTest.java | 420 ------- .../common/log/elements/LoggerSupportability.java | 4 + .../elements/AttributeDataDefinition.java | 9 + .../elements/GetOutputValueDataDefinition.java | 60 + .../be/datatypes/enums/ComponentFieldsEnum.java | 1 + .../openecomp-nosqldb-api/pom.xml | 6 +- .../openecomp-nosqldb-core/pom.xml | 12 +- .../openecomp-nosqldb-lib/pom.xml | 21 +- 48 files changed, 2576 insertions(+), 2394 deletions(-) create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentAttributeServlet.java create mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/servlets/OutputsServlet.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceOutput.java delete mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeInputCommon.java create mode 100644 catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeOutputCommon.java create mode 100644 common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetOutputValueDataDefinition.java diff --git a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigration.java b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigration.java index f0f59c4450..8796517c6e 100644 --- a/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigration.java +++ b/asdctool/src/main/java/org/openecomp/sdc/asdctool/migration/tasks/mig1806/ForwardPathMigration.java @@ -122,7 +122,7 @@ public class ForwardPathMigration implements Migration { componentParametersView.setIgnoreComponentInstances(false); componentParametersView.setIgnoreCapabilities(false); componentParametersView.setIgnoreRequirements(false); - componentParametersView.setIgnoreForwardingPath(false); + componentParametersView.setIgnoreServicePath(false); Either toscaElement = toscaOperationFacade .getToscaElement(container.getUniqueId(), componentParametersView); if (toscaElement.isRight()) { 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 cef4d8f6df..81e06a2138 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,10 +28,12 @@ import java.util.Optional; import org.apache.commons.lang3.tuple.ImmutablePair; 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.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; @@ -48,15 +50,13 @@ import org.openecomp.sdc.be.model.tosca.converters.PropertyValueConverter; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; /** * This class holds the business logic relevant for attributes manipulation. - * - * @author mshitrit * + * @author mshitrit */ -@Component("attributeBusinessLogic") +@org.springframework.stereotype.Component("attributeBusinessLogic") public class AttributeBusinessLogic extends BaseBusinessLogic { private static final String CREATE_ATTRIBUTE = "CreateAttribute"; @@ -68,12 +68,12 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { @Autowired public AttributeBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsOperations artifactToscaOperation) { + IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, + InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactsOperations artifactToscaOperation) { super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); } @@ -86,13 +86,16 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return AttributeDefinition if created successfully Or ResponseFormat */ - public Either createAttribute(String resourceId, AttributeDataDefinition newAttributeDef, String userId) { - Either result = null; + public Either createAttribute(String resourceId, + AttributeDefinition newAttributeDef, + String userId) { + Either result = null; validateUserExists(userId); StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + BeEcompErrorManager.getInstance() + .logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -112,11 +115,13 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { // verify attribute does not exist in resource if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName())); + return Either.right( + componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName())); } Map eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache); // validate property default values - Either defaultValuesValidation = validateAttributeDefaultValue(newAttributeDef, eitherAllDataTypes); + Either defaultValuesValidation = validateAttributeDefaultValue(newAttributeDef, + eitherAllDataTypes); if (defaultValuesValidation.isRight()) { return Either.right(defaultValuesValidation.right().value()); } @@ -126,9 +131,12 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { // add the new attribute to resource on graph // need to get StorageOperationStatus 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())); + result = Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), + resource.getName())); return result; } result = Either.left(either.left().value()); @@ -140,14 +148,15 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { } } - private Either validateAttributeDefaultValue(final AttributeDataDefinition attributeDefinition, + private Either validateAttributeDefaultValue(final AttributeDefinition attributeDefinition, final Map dataTypes) { - if (!attributeOperation.isAttributeTypeValid(attributeDefinition)) { - log.info("Invalid type for attribute '{}' type '{}'", attributeDefinition.getName(), attributeDefinition.getType()); - final ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, attributeDefinition - .getType(), attributeDefinition.getName()); + log.info("Invalid type for attribute '{}' type '{}'", attributeDefinition.getName(), + attributeDefinition.getType()); + final ResponseFormat responseFormat = componentsUtils + .getResponseFormat(ActionStatus.INVALID_PROPERTY_TYPE, attributeDefinition + .getType(), attributeDefinition.getName()); return Either.right(responseFormat); } String type = attributeDefinition.getType(); @@ -156,11 +165,12 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { final ImmutablePair propertyInnerTypeValid = attributeOperation.isAttributeInnerTypeValid( attributeDefinition, dataTypes); innerType = propertyInnerTypeValid.getLeft(); - if (!propertyInnerTypeValid.getRight()) { + if (!Boolean.TRUE.equals(propertyInnerTypeValid.getRight())) { log.info("Invalid inner type for attribute '{}' type '{}', dataTypeCount '{}'", attributeDefinition.getName(), attributeDefinition.getType(), dataTypes.size()); final ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, attributeDefinition.getName()); + .getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, + attributeDefinition.getName()); return Either.right(responseFormat); } } @@ -182,7 +192,7 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { return Either.left(true); } - private void handleAttributeDefaultValue(final AttributeDataDefinition newAttributeDefinition, + private void handleAttributeDefaultValue(final AttributeDefinition newAttributeDefinition, final Map dataTypes) { final ToscaPropertyType type = ToscaPropertyType.isValidType(newAttributeDefinition.getType()); final PropertyValueConverter converter = type.getConverter(); @@ -201,10 +211,11 @@ 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.getOwnerId(), resourceUid)); + isExist = attributes.stream().anyMatch( + p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getOwnerId(), resourceUid)); } return isExist; @@ -216,7 +227,8 @@ 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); @@ -227,14 +239,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 -> + Optional optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId)).findAny(); - return optionalAtt.>map(Either::left).orElseGet(() -> + return optionalAtt.>map(Either::left).orElseGet(() -> Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""))); } } @@ -248,12 +260,14 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { * @param userId * @return */ - public Either updateAttribute(String resourceId, String attributeId, AttributeDataDefinition newAttDef, String userId) { - Either result = null; + public Either updateAttribute(String resourceId, String attributeId, + AttributeDefinition newAttDef, String userId) { + Either result = null; StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + BeEcompErrorManager.getInstance() + .logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -271,30 +285,38 @@ 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 = validateAttributeDefaultValue(newAttDef, eitherAllDataTypes); + Either defaultValuesValidation = validateAttributeDefaultValue(newAttDef, + eitherAllDataTypes); if (defaultValuesValidation.isRight()) { return Either.right(defaultValuesValidation.right().value()); } // add the new property to resource on graph - StorageOperationStatus validateAndUpdateAttribute = attributeOperation.validateAndUpdateAttribute(newAttDef, eitherAllDataTypes); + StorageOperationStatus validateAndUpdateAttribute = attributeOperation + .validateAndUpdateAttribute(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())); + 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()); - result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName())); + log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, + eitherAttUpdate.right().value()); + result = Either.right(componentsUtils.getResponseFormatByResource( + componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName())); return result; } @@ -315,15 +337,17 @@ 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); StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource); if (lockResult != StorageOperationStatus.OK) { - BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); + BeEcompErrorManager.getInstance() + .logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId); log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } @@ -342,16 +366,20 @@ 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()); } String attributeName = eitherAttributeExist.left().value().getName(); // delete attribute of resource from graph - StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName); + StorageOperationStatus eitherAttributeDelete = toscaOperationFacade + .deleteAttributeOfResource(resource, attributeName); if (eitherAttributeDelete != StorageOperationStatus.OK) { - result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName())); + result = Either.right(componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), + resource.getName())); return result; } @@ -362,4 +390,21 @@ public class AttributeBusinessLogic extends BaseBusinessLogic { graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource); } } + + public Either, ResponseFormat> getAttributesList(final String componentId, + final String userId) { + validateUserExists(userId); + + // Get the resource from DB + final ComponentParametersView filter = new ComponentParametersView(true); + filter.setIgnoreAttributes(false); + final Either status = toscaOperationFacade.getToscaElement(componentId, filter); + if (status.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, "")); + } + + return Either.left(status.left().value().getAttributes()); + } + + } 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 be2a45b24f..0b04f70779 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,7 +49,6 @@ 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; @@ -59,6 +58,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; @@ -941,8 +941,8 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { log.debug("property {} cannot be overriden, check out performed without upgrading to latest generic", validPropertiesMerge.right().value()); return false; } - List genericTypeAttributes = latestGeneric.getAttributes(); - final Either, String> validAttributesMerge = validateNoConflictingProperties( + 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()); @@ -1038,5 +1038,3 @@ public abstract class ComponentBusinessLogic extends BaseBusinessLogic { } } - - 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 1104621379..5af6f41938 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 @@ -363,7 +363,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return createComponent(needLock, containerComponent,origComponent, resourceInstance, user); } - + private Component getOrigComponentForServiceProxy(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance resourceInstance) { Either serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy"); if (isServiceProxyOrigin(serviceProxyOrigin)) { @@ -378,14 +378,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { validateOriginAndResourceInstanceTypes(containerComponent, origComponent, OriginTypeEnum.ServiceProxy); return origComponent; } - + private Component getOrigComponentForServiceSubstitution(ComponentInstance resourceInstance) { final Either getServiceResult = toscaOperationFacade.getToscaFullElement(resourceInstance.getComponentUid()); if (getServiceResult.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); } final Component service = getServiceResult.left().value(); - + final Either getServiceDerivedFromTypeResult = toscaOperationFacade.getLatestByToscaResourceName(service.getDerivedFromGenericType()); if (getServiceDerivedFromTypeResult.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); @@ -658,6 +658,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { filter.setIgnoreRequirements(false); filter.setIgnoreInterfaces(false); filter.setIgnoreProperties(false); + filter.setIgnoreAttributes(false); filter.setIgnoreInputs(false); Either serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter); @@ -674,6 +675,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { serviceInterfaces.forEach(resourceInstance::addInterface); } resourceInstance.setProperties(PropertiesUtils.getProperties(service)); + resourceInstance.setAttributes(service.getAttributes()); final List serviceInputs = service.getInputs(); resourceInstance.setInputs(serviceInputs); @@ -683,17 +685,17 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resourceInstance.setSourceModelUid(service.getUniqueId()); resourceInstance.setComponentUid(origComponent.getUniqueId()); resourceInstance.setComponentVersion(service.getVersion()); - + switch(resourceInstance.getOriginType()) { case ServiceProxy: return fillProxyInstanceData(resourceInstance, origComponent, service); case ServiceSubstitution: return fillServiceSubstitutableNodeTypeData(resourceInstance, service); - default: + default: return StorageOperationStatus.OK; } } - + private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent, final Component service) { final String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX; final String toscaResourceName = ((Resource) origComponent).getToscaResourceName(); @@ -707,7 +709,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { resourceInstance.setDescription("A Proxy for Service " + service.getName()); return StorageOperationStatus.OK; } - + private StorageOperationStatus fillServiceSubstitutableNodeTypeData(final ComponentInstance resourceInstance, final Component service) { resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName())); resourceInstance.setName(ValidationUtils.normalizeComponentInstanceName(service.getName())); @@ -1288,7 +1290,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } return componentInstance; } - + /** * Try to modify the delete and return two cases * @@ -1441,7 +1443,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private Collection getForwardingPathDataDefinitions(String containerComponentId) { ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreForwardingPath(false); + filter.setIgnoreServicePath(false); Either forwardingPathOrigin = toscaOperationFacade .getToscaElement(containerComponentId, filter); return forwardingPathOrigin.left().value().getForwardingPaths().values(); @@ -2510,7 +2512,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private ComponentParametersView getComponentParametersViewForForwardingPath() { ComponentParametersView componentParametersView = new ComponentParametersView(); componentParametersView.setIgnoreCapabiltyProperties(false); - componentParametersView.setIgnoreForwardingPath(false); + componentParametersView.setIgnoreServicePath(false); return componentParametersView; } @@ -2602,14 +2604,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); } final Component service = getServiceResult.left().value(); - + final Either getServiceDerivedFromTypeResult = toscaOperationFacade.getLatestByToscaResourceName(service.getDerivedFromGenericType()); if (getServiceDerivedFromTypeResult.isRight()) { throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value())); } origComponent = getServiceDerivedFromTypeResult.left().value(); - + final StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent); if (isFillProxyRes(fillProxyRes)) { throw new ByActionStatusComponentException( @@ -2698,16 +2700,54 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { instanceProperties = new ArrayList<>(); } return instanceProperties; - }catch (ComponentException e){ + } catch (ComponentException e) { failed = true; throw e; - }finally { + } finally { + unlockComponent(failed, containerComponent); + } + } + + public List getComponentInstanceAttributesById(final String containerComponentTypeParam, + final String containerComponentId, + final String componentInstanceUniqueId, + final String userId) { + Component containerComponent = null; + + boolean failed = false; + try { + validateUserExists(userId); + validateComponentType(containerComponentTypeParam); + + final Either validateContainerComponentExists = + toscaOperationFacade.getToscaElement(containerComponentId); + if (validateContainerComponentExists.isRight()) { + throw new ByActionStatusComponentException( + componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value())); + } + containerComponent = validateContainerComponentExists.left().value(); + + if (getResourceInstanceById(containerComponent, componentInstanceUniqueId).isRight()) { + throw new ByActionStatusComponentException( + ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId); + } + + final Map> componentInstancesAttributes = containerComponent.getComponentInstancesAttributes(); + return componentInstancesAttributes == null ? new ArrayList<>() + : componentInstancesAttributes.getOrDefault(componentInstanceUniqueId, new ArrayList<>()); + } catch (final ComponentException e) { + failed = true; + throw e; + } finally { unlockComponent(failed, containerComponent); } } - protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper instaceCounterWrapper, Wrapper errorWrapper) { - Either counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true); + protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, + Wrapper instaceCounterWrapper, + Wrapper errorWrapper) { + Either counterRes = componentInstanceOperation + .increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true); if (counterRes.isRight()) { log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId); @@ -2889,10 +2929,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR); } } - + public Either updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, RequirementDefinition requirementDef, String userId) { - + Either resultOp = null; validateUserExists(userId); @@ -2922,7 +2962,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.debug("Failed to lock component {}", containerComponentId); return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); } - + try { StorageOperationStatus updateRequirementStatus = toscaOperationFacade.updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef); if (updateRequirementStatus != StorageOperationStatus.OK) { @@ -2947,7 +2987,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } // unlock resource graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); - } + } } public Either, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java new file mode 100644 index 0000000000..eecb6eeba2 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/OutputsBusinessLogic.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2021, Nordix Foundation. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import fj.data.Either; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.openecomp.sdc.be.components.validation.ComponentValidations; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceOutput; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; +import org.openecomp.sdc.be.model.operations.api.IGroupOperation; +import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; +import org.openecomp.sdc.common.log.elements.LoggerSupportability; +import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions; +import org.openecomp.sdc.common.log.enums.StatusCode; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.beans.factory.annotation.Autowired; + +@org.springframework.stereotype.Component("outputsBusinessLogic") +public class OutputsBusinessLogic extends BaseBusinessLogic { + + private static final Logger log = Logger.getLogger(OutputsBusinessLogic.class); + private static final String FAILED_TO_FOUND_COMPONENT_ERROR = "Failed to found component {}, error: {}"; + private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(OutputsBusinessLogic.class); + private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID = "Failed to found component instance outputs componentInstanceId: {}"; + private static final String FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR = "Failed to found component instance outputs {}, error: {}"; + + @Autowired + public OutputsBusinessLogic(final IElementOperation elementDao, + final IGroupOperation groupOperation, + final IGroupInstanceOperation groupInstanceOperation, + final IGroupTypeOperation groupTypeOperation, + final InterfaceOperation interfaceOperation, + final InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + final ArtifactsOperations artifactToscaOperation) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, + interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + } + + public Either, ResponseFormat> getComponentInstanceOutputs(final String userId, + final String componentId, + final String componentInstanceId) { + + validateUserExists(userId); + final ComponentParametersView filters = new ComponentParametersView(); + filters.disableAll(); + filters.setIgnoreOutputs(false); + filters.setIgnoreComponentInstances(false); + filters.setIgnoreComponentInstancesOutputs(false); + + final Either getComponentEither = toscaOperationFacade.getToscaElement(componentId, filters); + if (getComponentEither.isRight()) { + ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentEither.right().value()); + log.debug(FAILED_TO_FOUND_COMPONENT_ERROR, componentId, actionStatus); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + + } + final Component component = getComponentEither.left().value(); + + if (!ComponentValidations.validateComponentInstanceExist(component, componentInstanceId)) { + final ActionStatus actionStatus = ActionStatus.COMPONENT_INSTANCE_NOT_FOUND; + log.debug(FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_ERROR, componentInstanceId, actionStatus); + loggerSupportability.log(LoggerSupportabilityActions.CREATE_INPUTS, component.getComponentMetadataForSupportLog(), + StatusCode.ERROR, FAILED_TO_FOUND_COMPONENT_INSTANCE_OUTPUTS_COMPONENT_INSTANCE_ID, componentInstanceId); + return Either.right(componentsUtils.getResponseFormat(actionStatus)); + } + final Map> ciOutputs = Optional.ofNullable(component.getComponentInstancesOutputs()) + .orElse(Collections.emptyMap()); + + return Either.left(ciOutputs.getOrDefault(componentInstanceId, Collections.emptyList())); + } + +} 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 4c34ddaba0..80093bcf0a 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,7 +94,6 @@ 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; @@ -2632,7 +2631,7 @@ 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<>(); @@ -2693,7 +2692,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map> instArtifacts, Map> instProperties, Map> instInputs, - Map> instAttributes) { + Map> instAttributes) { Optional foundInstance = findInstance(oldResource, instance); if (foundInstance.isPresent()) { if (MapUtils.isNotEmpty(foundInstance.get().getCapabilities())) { @@ -2749,7 +2748,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { } private void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, - Map> instAttributes) { + Map> instAttributes) { StorageOperationStatus addArtToInst; addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, resource); @@ -2905,7 +2904,7 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { Map>> instRequirements, Map> instDeploymentArtifacts, Map> instArtifacts, - Map> instAttributes, + Map> instAttributes, Map originCompMap, Map> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) { 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 6137a3ffca..b2e4ef298f 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 @@ -60,7 +60,6 @@ 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.dao.janusgraph.JanusGraphOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; @@ -68,6 +67,7 @@ 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.ComponentInstanceProperty; import org.openecomp.sdc.be.model.DataTypeDefinition; @@ -111,6 +111,7 @@ public class ResourceImportManager { private AuditingManager auditingManager; private ResourceBusinessLogic resourceBusinessLogic; + public ServiceBusinessLogic getServiceBusinessLogic() { return serviceBusinessLogic; } @@ -243,7 +244,7 @@ public class ResourceImportManager { componentsUtils .getResponseFormat(((ComponentException) e).getActionStatus(), ((ComponentException) e).getParams()) : - ((ComponentException) e).getResponseFormat(); + ((ComponentException) e).getResponseFormat(); } return null; } @@ -686,8 +687,8 @@ public class ResourceImportManager { log.debug("Couldn't check whether imported resource capability derives from its parent's capability"); throw new ByActionStatusComponentException( componentsUtils.convertFromStorageResponse(capabilityTypeDerivedFrom - .right() - .value())); + .right() + .value())); } return capabilityTypeDerivedFrom.left().value(); } @@ -712,7 +713,7 @@ public class ResourceImportManager { if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES.getElementName())) { capabilityDefinition.setValidSourceTypes( (List) capabilityJsonMap.get(TypeUtils.ToscaTagNamesEnum.VALID_SOURCE_TYPES - .getElementName())); + .getElementName())); } // ValidSourceTypes if (capabilityJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.DESCRIPTION.getElementName())) { @@ -830,10 +831,10 @@ public class ResourceImportManager { calculateResourceIsAbstract(resource, categories); } - private List getAttributes(final String payloadData) { + private List getAttributes(final String payloadData) { final Map mappedToscaTemplate = decodePayload(payloadData); - final List attributeDataDefinitionList = new ArrayList<>(); + final List attributeDataDefinitionList = new ArrayList<>(); final Either, ResultStatusEnum> firstToscaMapElement = ImportUtils .findFirstToscaMapElement(mappedToscaTemplate, ToscaTagNamesEnum.ATTRIBUTES); @@ -851,7 +852,7 @@ public class ResourceImportManager { final Map attributeMap = (Map) value; - final AttributeDataDefinition attributeDefinition = new AttributeDataDefinition(); + final AttributeDefinition attributeDefinition = new AttributeDefinition(); attributeDefinition.setName(key); setField(attributeMap, ToscaTagNamesEnum.DESCRIPTION, attributeDefinition::setDescription); @@ -861,7 +862,7 @@ public class ResourceImportManager { setField(attributeMap, ToscaTagNamesEnum.ENTRY_SCHEMA, attributeDefinition::setSchema); attributeDataDefinitionList.add(attributeDefinition); } else { - final AttributeDataDefinition attributeDefinition = new AttributeDataDefinition(); + final AttributeDefinition attributeDefinition = new AttributeDefinition(); attributeDefinition.setName(key); attributeDataDefinitionList.add(attributeDefinition); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java index 550e2d9ea0..507abb5ed6 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogic.java @@ -69,7 +69,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datamodel.utils.ArtifactUtils; import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; @@ -79,6 +78,7 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; 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.Component; @@ -139,7 +139,7 @@ import org.yaml.snakeyaml.Yaml; @Getter @Setter @org.springframework.stereotype.Component("serviceImportBusinessLogic") -public class ServiceImportBusinessLogic{ +public class ServiceImportBusinessLogic { private final UiComponentDataConverter uiComponentDataConverter; private static final String INITIAL_VERSION = "0.1"; @@ -153,15 +153,14 @@ public class ServiceImportBusinessLogic{ private static final String CREATE_RESOURCE_VALIDATE_CAPABILITY_TYPES = "Create Resource - validateCapabilityTypesCreate"; private static final String CATEGORY_IS_EMPTY = "Resource category is empty"; - @Autowired private ServiceBusinessLogic serviceBusinessLogic; + public ServiceBusinessLogic getServiceBusinessLogic() { return serviceBusinessLogic; } - public void setServiceBusinessLogic( - ServiceBusinessLogic serviceBusinessLogic) { + public void setServiceBusinessLogic(ServiceBusinessLogic serviceBusinessLogic) { this.serviceBusinessLogic = serviceBusinessLogic; } @@ -183,33 +182,35 @@ public class ServiceImportBusinessLogic{ private ServiceImportParseLogic serviceImportParseLogic; private static final Logger log = Logger.getLogger(ServiceImportBusinessLogic.class); + @Autowired public ServiceImportBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsBusinessLogic artifactsBusinessLogic, - IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, - ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator, - UiComponentDataConverter uiComponentDataConverter, NodeFilterOperation serviceFilterOperation, - NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation, - ComponentContactIdValidator componentContactIdValidator, - ComponentNameValidator componentNameValidator, - ComponentTagsValidator componentTagsValidator, - ComponentValidator componentValidator, - ComponentIconValidator componentIconValidator, - ComponentProjectCodeValidator componentProjectCodeValidator, - ComponentDescriptionValidator componentDescriptionValidator) { + IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, + GroupBusinessLogic groupBusinessLogic, + InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactsBusinessLogic artifactsBusinessLogic, + IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, + ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator, + UiComponentDataConverter uiComponentDataConverter, NodeFilterOperation serviceFilterOperation, + NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation, + ComponentContactIdValidator componentContactIdValidator, + ComponentNameValidator componentNameValidator, + ComponentTagsValidator componentTagsValidator, + ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, + ComponentProjectCodeValidator componentProjectCodeValidator, + ComponentDescriptionValidator componentDescriptionValidator) { this.componentInstanceBusinessLogic = componentInstanceBusinessLogic; this.uiComponentDataConverter = uiComponentDataConverter; } private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - public Service createService(Service service, AuditingActionEnum auditingAction, User user, Map csarUIPayload, String payloadName) { + public Service createService(Service service, AuditingActionEnum auditingAction, User user, Map csarUIPayload, + String payloadName) { log.debug("enter createService"); service.setCreatorUserId(user.getUserId()); service.setState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); @@ -230,9 +231,8 @@ public class ServiceImportBusinessLogic{ csarBusinessLogic.validateCsarBeforeCreate(service, csarUUID); log.debug("CsarUUID is {} - going to create resource from CSAR", csarUUID); return createServiceFromCsar(service, user, csarUIPayload, csarUUID); - }catch (Exception e){ - log.debug("Exception occured when createService,error is:{}",e.getMessage(),e); - //ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); + } catch (Exception e) { + log.debug("Exception occured when createService,error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } } @@ -244,34 +244,34 @@ public class ServiceImportBusinessLogic{ Map nodeTypesInfo = csarInfo.extractNodeTypesInfo(); Either>>, ResponseFormat> findNodeTypesArtifactsToHandleRes = serviceImportParseLogic - .findNodeTypesArtifactsToHandle( - nodeTypesInfo, csarInfo, service); + .findNodeTypesArtifactsToHandle( + nodeTypesInfo, csarInfo, service); if (findNodeTypesArtifactsToHandleRes.isRight()) { log.debug("failed to find node types for update with artifacts during import csar {}. ", - csarInfo.getCsarUUID()); + csarInfo.getCsarUUID()); throw new ComponentException(findNodeTypesArtifactsToHandleRes.right().value()); } - Service cService = createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), - nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, - null); - return cService; - }catch (Exception e){ - log.debug("Exception occured when createServiceFromCsar,error is:{}",e.getMessage(),e); + return createServiceFromYaml(service, csarInfo.getMainTemplateContent(), csarInfo.getMainTemplateName(), + nodeTypesInfo, csarInfo, findNodeTypesArtifactsToHandleRes.left().value(), true, false, + null); + } catch (Exception e) { + log.debug("Exception occured when createServiceFromCsar,error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } } protected Service createServiceFromYaml(Service service, String topologyTemplateYaml, - String yamlName, Map nodeTypesInfo, CsarInfo csarInfo, - Map>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { + String yamlName, Map nodeTypesInfo, CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { List createdArtifacts = new ArrayList<>(); Service createdService; CreateServiceFromYamlParameter csfyp = new CreateServiceFromYamlParameter(); try { ParsedToscaYamlInfo - parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, service); + parsedToscaYamlInfo = csarBusinessLogic + .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, service); if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances())) { throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } @@ -297,8 +297,8 @@ public class ServiceImportBusinessLogic{ } protected Service createServiceAndRIsFromYaml(Service service, boolean isNormative, - Map>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, CreateServiceFromYamlParameter csfyp) { + Map>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, CreateServiceFromYamlParameter csfyp) { List nodeTypesNewCreatedArtifacts = new ArrayList<>(); String yamlName = csfyp.getYamlName(); @@ -327,15 +327,15 @@ public class ServiceImportBusinessLogic{ log.trace("************* Finish to add inputs from yaml {}", yamlName); Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo - .getInstances(); + .getInstances(); log.trace("************* Going to create nodes, RI's and Relations from yaml {}", yamlName); service = createRIAndRelationsFromYaml(yamlName, service, uploadComponentInstanceInfoMap, - topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, - nodeTypesArtifactsToCreate, nodeName); + topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeTypesArtifactsToCreate, nodeName); log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); Either, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic - .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), service.getSystemName()); + .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), service.getSystemName()); if (validateUpdateVfGroupNamesRes.isRight()) { serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(validateUpdateVfGroupNamesRes.right().value()); @@ -358,11 +358,11 @@ public class ServiceImportBusinessLogic{ log.trace("************* Going to add artifacts from yaml {}", yamlName); NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, - nodeTypesArtifactsToCreate); + nodeTypesArtifactsToCreate); Either createArtifactsEither = createOrUpdateArtifacts( - ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, - csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, + csarInfo, service, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); if (createArtifactsEither.isRight()) { serviceImportParseLogic.rollback(inTransaction, service, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(createArtifactsEither.right().value()); @@ -379,32 +379,33 @@ public class ServiceImportBusinessLogic{ } if (shouldLock) { serviceBusinessLogic.graphLockOperation.unlockComponentByName(service.getSystemName(), service.getUniqueId(), - NodeTypeEnum.Resource); + NodeTypeEnum.Resource); } } } protected Either createOrUpdateArtifacts( - ArtifactsBusinessLogic.ArtifactOperationEnum operation, List createdArtifacts, - String yamlFileName, CsarInfo csarInfo, Resource preparedResource, - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) { + ArtifactsBusinessLogic.ArtifactOperationEnum operation, List createdArtifacts, + String yamlFileName, CsarInfo csarInfo, Resource preparedResource, + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) { String nodeName = nodeTypeInfoToUpdateArtifacts.getNodeName(); Resource resource = preparedResource; Map>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts - .getNodeTypesArtifactsToHandle(); + .getNodeTypesArtifactsToHandle(); if (preparedResource.getResourceType() == ResourceTypeEnum.VF) { if (nodeName != null && nodeTypesArtifactsToHandle.get(nodeName) != null && !nodeTypesArtifactsToHandle.get(nodeName).isEmpty()) { Either, ResponseFormat> handleNodeTypeArtifactsRes = - handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), inTransaction, true); + handleNodeTypeArtifacts(preparedResource, nodeTypesArtifactsToHandle.get(nodeName), createdArtifacts, csarInfo.getModifier(), + inTransaction, true); if (handleNodeTypeArtifactsRes.isRight()) { return Either.right(handleNodeTypeArtifactsRes.right().value()); } } } else { Either createdCsarArtifactsEither = handleVfCsarArtifacts(preparedResource, csarInfo, createdArtifacts, - new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction); + new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction); log.trace("************* Finished to add artifacts from yaml {}", yamlFileName); if (createdCsarArtifactsEither.isRight()) { return createdCsarArtifactsEither; @@ -415,27 +416,30 @@ public class ServiceImportBusinessLogic{ } protected Either handleVfCsarArtifacts(Resource resource, CsarInfo csarInfo, - List createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, - boolean inTransaction) { + List createdArtifacts, + ArtifactOperationInfo artifactOperation, boolean shouldLock, + boolean inTransaction) { if (csarInfo.getCsar() != null) { createOrUpdateSingleNonMetaArtifactToComstants(resource, csarInfo, artifactOperation, shouldLock, inTransaction); Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, resource, - createdArtifacts, shouldLock, inTransaction, artifactOperation); + createdArtifacts, shouldLock, inTransaction, artifactOperation); if (eitherCreateResult.isRight()) { return Either.right(eitherCreateResult.right().value()); } Either eitherGerResource = toscaOperationFacade.getToscaElement(resource.getUniqueId()); if (eitherGerResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), resource); return Either.right(responseFormat); } resource = eitherGerResource.left().value(); - Either, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); + Either, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils + .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); if (artifacsMetaCsarStatus.isLeft()) { - return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction, artifacsMetaCsarStatus); + return getResourceResponseFormatEither(resource, csarInfo, createdArtifacts, artifactOperation, shouldLock, inTransaction, + artifacsMetaCsarStatus); } else { return csarArtifactsAndGroupsBusinessLogic.deleteVFModules(resource, csarInfo, shouldLock, inTransaction); } @@ -443,7 +447,8 @@ public class ServiceImportBusinessLogic{ return Either.left(resource); } - protected void createOrUpdateSingleNonMetaArtifactToComstants(Resource resource, CsarInfo csarInfo, ArtifactOperationInfo artifactOperation, boolean shouldLock, boolean inTransaction) { + protected void createOrUpdateSingleNonMetaArtifactToComstants(Resource resource, CsarInfo csarInfo, ArtifactOperationInfo artifactOperation, + boolean shouldLock, boolean inTransaction) { String vendorLicenseModelId = null; String vfLicenseModelId = null; if (artifactOperation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) { @@ -460,19 +465,23 @@ public class ServiceImportBusinessLogic{ } } createOrUpdateSingleNonMetaArtifact(resource, csarInfo, - CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, - ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, - Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, - Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock, - inTransaction); + CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, + ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, + Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, + Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock, + inTransaction); createOrUpdateSingleNonMetaArtifact(resource, csarInfo, - CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, - ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, - Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, - artifactOperation, null, true, shouldLock, inTransaction); + CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, + ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, + Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, + artifactOperation, null, true, shouldLock, inTransaction); } - protected Either getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo, List createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, boolean inTransaction, Either, ResponseFormat> artifacsMetaCsarStatus) { + protected Either getResourceResponseFormatEither(Resource resource, CsarInfo csarInfo, + List createdArtifacts, + ArtifactOperationInfo artifactOperation, boolean shouldLock, + boolean inTransaction, + Either, ResponseFormat> artifacsMetaCsarStatus) { try { String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey(); String artifactsContents = artifacsMetaCsarStatus.left().value().getValue(); @@ -497,22 +506,23 @@ public class ServiceImportBusinessLogic{ return Either.right(createArtifactsFromCsar.right().value()); } return Either.left(createArtifactsFromCsar.left().value()); - }catch(Exception e) { + } catch (Exception e) { log.debug("Exception occured in getResourceResponseFormatEither, message:{}", e.getMessage(), e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } } private Either createOrUpdateNonMetaArtifactsComp(CsarInfo csarInfo, T component, - List createdArtifacts, boolean shouldLock, boolean inTransaction, - ArtifactOperationInfo artifactOperation) { + List createdArtifacts, + boolean shouldLock, boolean inTransaction, + ArtifactOperationInfo artifactOperation) { Either resStatus = null; Map>> collectedWarningMessages = new HashMap<>(); try { Either, String> artifactPathAndNameList = getValidArtifactNames(csarInfo, collectedWarningMessages); if (artifactPathAndNameList.isRight()) { return Either.right(getComponentsUtils().getResponseFormatByArtifactId( - ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value())); + ActionStatus.ARTIFACT_NAME_INVALID, artifactPathAndNameList.right().value())); } EnumMap> vfCsarArtifactsToHandle = null; @@ -521,7 +531,7 @@ public class ServiceImportBusinessLogic{ vfCsarArtifactsToHandle.put(artifactOperation.getArtifactOperationEnum(), artifactPathAndNameList.left().value()); } else { Either>, ResponseFormat> findVfCsarArtifactsToHandleRes = findVfCsarArtifactsToHandle( - component, artifactPathAndNameList.left().value(), csarInfo.getModifier()); + component, artifactPathAndNameList.left().value(), csarInfo.getModifier()); if (findVfCsarArtifactsToHandleRes.isRight()) { resStatus = Either.right(findVfCsarArtifactsToHandleRes.right().value()); } @@ -530,7 +540,8 @@ public class ServiceImportBusinessLogic{ } } if (resStatus == null && vfCsarArtifactsToHandle != null) { - resStatus = processCsarArtifacts(csarInfo, component, createdArtifacts, shouldLock, inTransaction, resStatus, vfCsarArtifactsToHandle); + resStatus = processCsarArtifacts(csarInfo, component, createdArtifacts, shouldLock, inTransaction, resStatus, + vfCsarArtifactsToHandle); } if (resStatus == null) { resStatus = Either.left(component); @@ -545,27 +556,31 @@ public class ServiceImportBusinessLogic{ } protected Either createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Resource resource, - List createdArtifacts, boolean shouldLock, boolean inTransaction, - ArtifactOperationInfo artifactOperation) { + List createdArtifacts, boolean shouldLock, + boolean inTransaction, + ArtifactOperationInfo artifactOperation) { return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation); } - protected Either processCsarArtifacts(CsarInfo csarInfo, Component comp, List createdArtifacts, boolean shouldLock, boolean inTransaction, - Either resStatus, EnumMap> vfCsarArtifactsToHandle) { + protected Either processCsarArtifacts(CsarInfo csarInfo, Component comp, + List createdArtifacts, boolean shouldLock, + boolean inTransaction, + Either resStatus, + EnumMap> vfCsarArtifactsToHandle) { for (Map.Entry> currArtifactOperationPair : vfCsarArtifactsToHandle - .entrySet()) { + .entrySet()) { Optional optionalCreateInDBError = - currArtifactOperationPair.getValue().stream() - .map(e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), - e.getArtifactName(), e.getArtifactType(), - e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), - CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), - new ArtifactOperationInfo(false, false, - currArtifactOperationPair.getKey()), - createdArtifacts, e.isFromCsar(), shouldLock, inTransaction)) - .filter(Either::isRight). - map(e -> e.right().value()). - findAny(); + currArtifactOperationPair.getValue().stream() + .map(e -> createOrUpdateSingleNonMetaArtifact(comp, csarInfo, e.getPath(), + e.getArtifactName(), e.getArtifactType(), + e.getArtifactGroupType(), e.getArtifactLabel(), e.getDisplayName(), + CsarUtils.ARTIFACT_CREATED_FROM_CSAR, e.getArtifactUniqueId(), + new ArtifactOperationInfo(false, false, + currArtifactOperationPair.getKey()), + createdArtifacts, e.isFromCsar(), shouldLock, inTransaction)) + .filter(Either::isRight). + map(e -> e.right().value()). + findAny(); if (optionalCreateInDBError.isPresent()) { resStatus = Either.right(optionalCreateInDBError.get()); break; @@ -575,9 +590,13 @@ public class ServiceImportBusinessLogic{ } protected Either createOrUpdateSingleNonMetaArtifact(Component component, CsarInfo csarInfo, - String artifactPath, String artifactFileName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, - String artifactLabel, String artifactDisplayName, String artifactDescription, String artifactId, - ArtifactOperationInfo operation, List createdArtifacts, boolean isFromCsar, boolean shouldLock, + String artifactPath, String artifactFileName, String artifactType, + ArtifactGroupTypeEnum artifactGroupType, + String artifactLabel, String artifactDisplayName, + String artifactDescription, String artifactId, + ArtifactOperationInfo operation, + List createdArtifacts, boolean isFromCsar, + boolean shouldLock, boolean inTransaction) { byte[] artifactFileBytes = null; @@ -585,9 +604,11 @@ public class ServiceImportBusinessLogic{ artifactFileBytes = csarInfo.getCsar().get(artifactPath); } Either result = Either.left(true); - if (operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) { + if (operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE + || operation.getArtifactOperationEnum() == ArtifactsBusinessLogic.ArtifactOperationEnum.DELETE) { if (serviceImportParseLogic.isArtifactDeletionRequired(artifactId, artifactFileBytes, isFromCsar)) { - Either handleDelete = serviceBusinessLogic.artifactsBusinessLogic.handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, + Either handleDelete = serviceBusinessLogic.artifactsBusinessLogic + .handleDelete(component.getUniqueId(), artifactId, csarInfo.getModifier(), component, shouldLock, inTransaction); if (handleDelete.isRight()) { result = Either.right(handleDelete.right().value()); @@ -596,23 +617,24 @@ public class ServiceImportBusinessLogic{ } if (org.apache.commons.lang.StringUtils.isEmpty(artifactId) && artifactFileBytes != null) { operation = new ArtifactOperationInfo(false, false, - ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE); + ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE); } } if (artifactFileBytes != null) { Map vendorLicenseModelJson = ArtifactUtils - .buildJsonForUpdateArtifact(artifactId, artifactFileName, - artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, - artifactFileBytes, null, isFromCsar); - Either, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic.createOrUpdateCsarArtifactFromJson( + .buildJsonForUpdateArtifact(artifactId, artifactFileName, + artifactType, artifactGroupType, artifactLabel, artifactDisplayName, artifactDescription, + artifactFileBytes, null, isFromCsar); + Either, ResponseFormat> eitherNonMetaArtifacts = csarArtifactsAndGroupsBusinessLogic + .createOrUpdateCsarArtifactFromJson( component, csarInfo.getModifier(), vendorLicenseModelJson, operation); serviceImportParseLogic - .addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); + .addNonMetaCreatedArtifactsToSupportRollback(operation, createdArtifacts, eitherNonMetaArtifacts); if (eitherNonMetaArtifacts.isRight()) { BeEcompErrorManager.getInstance() - .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " - + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), - BeEcompErrorManager.ErrorSeverity.WARNING); + .logInternalFlowError("UploadLicenseArtifact", "Failed to upload license artifact: " + + artifactFileName + "With csar uuid: " + csarInfo.getCsarUUID(), + BeEcompErrorManager.ErrorSeverity.WARNING); return Either.right(eitherNonMetaArtifacts.right().value()); } } @@ -621,7 +643,8 @@ public class ServiceImportBusinessLogic{ public Either, ResponseFormat> handleNodeTypeArtifacts(Resource nodeTypeResource, Map> nodeTypeArtifactsToHandle, - List createdArtifacts, User user, boolean inTransaction, boolean ignoreLifecycleState) { + List createdArtifacts, User user, + boolean inTransaction, boolean ignoreLifecycleState) { List handleNodeTypeArtifactsRequestRes; Either, ResponseFormat> handleNodeTypeArtifactsRes = null; Either changeStateResponse; @@ -635,17 +658,17 @@ public class ServiceImportBusinessLogic{ List handledNodeTypeArtifacts = new ArrayList<>(); log.debug("************* Going to handle artifacts of node type resource {}. ", nodeTypeResource.getName()); for (Map.Entry> curOperationEntry : nodeTypeArtifactsToHandle - .entrySet()) { + .entrySet()) { ArtifactsBusinessLogic.ArtifactOperationEnum curOperation = curOperationEntry.getKey(); List curArtifactsToHandle = curOperationEntry.getValue(); if (curArtifactsToHandle != null && !curArtifactsToHandle.isEmpty()) { log.debug("************* Going to {} artifact to vfc {}", curOperation.name(), - nodeTypeResource.getName()); + nodeTypeResource.getName()); handleNodeTypeArtifactsRequestRes = serviceBusinessLogic.artifactsBusinessLogic - .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, - createdArtifacts, new ArtifactOperationInfo(false, - ignoreLifecycleState, curOperation), - false, inTransaction); + .handleArtifactsRequestForInnerVfcComponent(curArtifactsToHandle, nodeTypeResource, user, + createdArtifacts, new ArtifactOperationInfo(false, + ignoreLifecycleState, curOperation), + false, inTransaction); if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(curOperation)) { createdArtifacts.addAll(handleNodeTypeArtifactsRequestRes); } @@ -667,12 +690,12 @@ public class ServiceImportBusinessLogic{ Either checkoutResourceRes; try { if (!resource.getComponentMetadataDefinition().getMetadataDataDefinition().getState() - .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { + .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { Either checkoutRes = lifecycleBusinessLogic.changeComponentState( - resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, - new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, - LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), - inTransaction, true); + resource.getComponentType(), resource.getUniqueId(), user, LifeCycleTransitionEnum.CHECKOUT, + new LifecycleChangeInfoWithAction(CERTIFICATION_ON_IMPORT, + LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR), + inTransaction, true); if (checkoutRes.isRight()) { checkoutResourceRes = Either.right(checkoutRes.right().value()); } else { @@ -685,33 +708,30 @@ public class ServiceImportBusinessLogic{ ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR); checkoutResourceRes = Either.right(responseFormat); log.debug("Exception occured when checkoutResource {} , error is:{}", resource.getName(), e.getMessage(), - e); + e); } return checkoutResourceRes; } protected Either createOrUpdateArtifacts( - ArtifactsBusinessLogic.ArtifactOperationEnum operation, List createdArtifacts, - String yamlFileName, CsarInfo csarInfo, Service preparedService, - NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) { - - Service resource = preparedService; - Map>> nodeTypesArtifactsToHandle = nodeTypeInfoToUpdateArtifacts - .getNodeTypesArtifactsToHandle(); + ArtifactOperationEnum operation, List createdArtifacts, + String yamlFileName, CsarInfo csarInfo, Service preparedService, + NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts, boolean inTransaction, boolean shouldLock) { Either createdCsarArtifactsEither = handleVfCsarArtifacts(preparedService, csarInfo, createdArtifacts, - new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction); + new ArtifactOperationInfo(false, false, operation), shouldLock, inTransaction); log.trace("************* Finished to add artifacts from yaml {}", yamlFileName); if (createdCsarArtifactsEither.isRight()) { return createdCsarArtifactsEither; } - resource = createdCsarArtifactsEither.left().value(); - return Either.left(resource); + + return Either.left(createdCsarArtifactsEither.left().value()); } protected Either handleVfCsarArtifacts(Service service, CsarInfo csarInfo, - List createdArtifacts, ArtifactOperationInfo artifactOperation, boolean shouldLock, - boolean inTransaction) { + List createdArtifacts, + ArtifactOperationInfo artifactOperation, boolean shouldLock, + boolean inTransaction) { if (csarInfo.getCsar() != null) { String vendorLicenseModelId = null; @@ -730,40 +750,44 @@ public class ServiceImportBusinessLogic{ } } createOrUpdateSingleNonMetaArtifact(service, csarInfo, - CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, - ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, - Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, - Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock, - inTransaction); + CsarUtils.ARTIFACTS_PATH + Constants.VENDOR_LICENSE_MODEL, Constants.VENDOR_LICENSE_MODEL, + ArtifactTypeEnum.VENDOR_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, + Constants.VENDOR_LICENSE_LABEL, Constants.VENDOR_LICENSE_DISPLAY_NAME, + Constants.VENDOR_LICENSE_DESCRIPTION, vendorLicenseModelId, artifactOperation, null, true, shouldLock, + inTransaction); createOrUpdateSingleNonMetaArtifact(service, csarInfo, - CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, - ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, - Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, - artifactOperation, null, true, shouldLock, inTransaction); + CsarUtils.ARTIFACTS_PATH + Constants.VF_LICENSE_MODEL, Constants.VF_LICENSE_MODEL, + ArtifactTypeEnum.VF_LICENSE.getType(), ArtifactGroupTypeEnum.DEPLOYMENT, Constants.VF_LICENSE_LABEL, + Constants.VF_LICENSE_DISPLAY_NAME, Constants.VF_LICENSE_DESCRIPTION, vfLicenseModelId, + artifactOperation, null, true, shouldLock, inTransaction); Either eitherCreateResult = createOrUpdateNonMetaArtifacts(csarInfo, service, - createdArtifacts, shouldLock, inTransaction, artifactOperation); + createdArtifacts, shouldLock, inTransaction, artifactOperation); if (eitherCreateResult.isRight()) { return Either.right(eitherCreateResult.right().value()); } Either eitherGerResource = toscaOperationFacade - .getToscaElement(service.getUniqueId()); + .getToscaElement(service.getUniqueId()); if (eitherGerResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service, ComponentTypeEnum.SERVICE); + componentsUtils.convertFromStorageResponse(eitherGerResource.right().value()), service, ComponentTypeEnum.SERVICE); return Either.right(responseFormat); } service = eitherGerResource.left().value(); - Either, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils.getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); + Either, ResponseFormat> artifacsMetaCsarStatus = CsarValidationUtils + .getArtifactsMeta(csarInfo.getCsar(), csarInfo.getCsarUUID(), componentsUtils); if (artifacsMetaCsarStatus.isLeft()) { String artifactsFileName = artifacsMetaCsarStatus.left().value().getKey(); String artifactsContents = artifacsMetaCsarStatus.left().value().getValue(); Either createArtifactsFromCsar; if (ArtifactsBusinessLogic.ArtifactOperationEnum.isCreateOrLink(artifactOperation.getArtifactOperationEnum())) { - createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic.createResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts); + createArtifactsFromCsar = csarArtifactsAndGroupsBusinessLogic + .createResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts); } else { - Either result = csarArtifactsAndGroupsBusinessLogic.updateResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, inTransaction); + Either result = csarArtifactsAndGroupsBusinessLogic + .updateResourceArtifactsFromCsar(csarInfo, service, artifactsContents, artifactsFileName, createdArtifacts, shouldLock, + inTransaction); if ((result.left().value() instanceof Service) && result.isLeft()) { Service service1 = (Service) result.left().value(); createArtifactsFromCsar = Either.left(service1); @@ -784,13 +808,14 @@ public class ServiceImportBusinessLogic{ } protected Either createOrUpdateNonMetaArtifacts(CsarInfo csarInfo, Service resource, - List createdArtifacts, boolean shouldLock, boolean inTransaction, - ArtifactOperationInfo artifactOperation) { + List createdArtifacts, boolean shouldLock, + boolean inTransaction, + ArtifactOperationInfo artifactOperation) { return createOrUpdateNonMetaArtifactsComp(csarInfo, resource, createdArtifacts, shouldLock, inTransaction, artifactOperation); } protected Either>, ResponseFormat> findVfCsarArtifactsToHandle( - Component component, List artifactPathAndNameList, User user) { + Component component, List artifactPathAndNameList, User user) { List existingArtifacts = new ArrayList<>(); if (component.getDeploymentArtifacts() != null && !component.getDeploymentArtifacts().isEmpty()) { existingArtifacts.addAll(component.getDeploymentArtifacts().values()); @@ -809,7 +834,7 @@ public class ServiceImportBusinessLogic{ }); } existingArtifacts = existingArtifacts.stream() - .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList()); + .filter(a -> !artifactsToIgnore.contains(a.getUniqueId())).collect(toList()); return organizeVfCsarArtifactsByArtifactOperation(artifactPathAndNameList, existingArtifacts, component, user); } @@ -824,20 +849,21 @@ public class ServiceImportBusinessLogic{ private boolean isValidArtifactType(ArtifactDefinition artifact) { boolean result = true; if (artifact.getArtifactType() == null - || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VENDOR_LICENSE) - || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VF_LICENSE)) { + || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VENDOR_LICENSE) + || ArtifactTypeEnum.findType(artifact.getArtifactType()).equals(ArtifactTypeEnum.VF_LICENSE)) { result = false; } return result; } + protected Either>, ResponseFormat> organizeVfCsarArtifactsByArtifactOperation( - List artifactPathAndNameList, List existingArtifactsToHandle, - Component component, User user) { + List artifactPathAndNameList, List existingArtifactsToHandle, + Component component, User user) { EnumMap> nodeTypeArtifactsToHandle = new EnumMap<>( - ArtifactsBusinessLogic.ArtifactOperationEnum.class); + ArtifactsBusinessLogic.ArtifactOperationEnum.class); Wrapper responseWrapper = new Wrapper<>(); Either>, ResponseFormat> nodeTypeArtifactsToHandleRes = Either - .left(nodeTypeArtifactsToHandle); + .left(nodeTypeArtifactsToHandle); try { List artifactsToUpload = new ArrayList<>(artifactPathAndNameList); List artifactsToUpdate = new ArrayList<>(); @@ -847,11 +873,11 @@ public class ServiceImportBusinessLogic{ if (!existingArtifactsToHandle.isEmpty()) { foundArtifact = existingArtifactsToHandle.stream() - .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst() - .orElse(null); + .filter(a -> a.getArtifactName().equals(currNewArtifact.getArtifactName())).findFirst() + .orElse(null); if (foundArtifact != null) { if (ArtifactTypeEnum.findType(foundArtifact.getArtifactType()).equals(currNewArtifact - .getArtifactType())) { + .getArtifactType())) { if (!foundArtifact.getArtifactChecksum().equals(currNewArtifact.getArtifactChecksum())) { currNewArtifact.setArtifactUniqueId(foundArtifact.getUniqueId()); artifactsToUpdate.add(currNewArtifact); @@ -860,17 +886,17 @@ public class ServiceImportBusinessLogic{ artifactsToUpload.remove(currNewArtifact); } else { log.debug("Can't upload two artifact with the same name {}.", - currNewArtifact.getArtifactName()); + currNewArtifact.getArtifactName()); ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat( - ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, - currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), - foundArtifact.getArtifactType()); + ActionStatus.ARTIFACT_ALREADY_EXIST_IN_DIFFERENT_TYPE_IN_CSAR, + currNewArtifact.getArtifactName(), currNewArtifact.getArtifactType(), + foundArtifact.getArtifactType()); AuditingActionEnum auditingAction = serviceBusinessLogic.artifactsBusinessLogic - .detectAuditingType(new ArtifactOperationInfo(false, false, - ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum()); + .detectAuditingType(new ArtifactOperationInfo(false, false, + ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE), foundArtifact.getArtifactChecksum()); serviceBusinessLogic.artifactsBusinessLogic.handleAuditing(auditingAction, component, component.getUniqueId(), - user, null, null, foundArtifact.getUniqueId(), responseFormat, - component.getComponentType(), null); + user, null, null, foundArtifact.getUniqueId(), responseFormat, + component.getComponentType(), null); responseWrapper.setInnerElement(responseFormat); break; } @@ -880,9 +906,13 @@ public class ServiceImportBusinessLogic{ if (responseWrapper.isEmpty()) { for (ArtifactDefinition currArtifact : existingArtifactsToHandle) { if (currArtifact.getIsFromCsar()) { - artifactsToDelete.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); + artifactsToDelete.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null, + ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, + currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); } else { - artifactsToUpdate.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null, ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); + artifactsToUpdate.add(new CsarUtils.NonMetaArtifactInfo(currArtifact.getArtifactName(), null, + ArtifactTypeEnum.findType(currArtifact.getArtifactType()), currArtifact.getArtifactGroupType(), null, + currArtifact.getUniqueId(), currArtifact.getIsFromCsar())); } } } @@ -918,16 +948,17 @@ public class ServiceImportBusinessLogic{ this.componentsUtils = componentsUtils; } - protected Either, String> getValidArtifactNames(CsarInfo csarInfo, Map>> collectedWarningMessages) { + protected Either, String> getValidArtifactNames(CsarInfo csarInfo, + Map>> collectedWarningMessages) { List artifactPathAndNameList = - csarInfo.getCsar().entrySet().stream() - .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()) - .matches()) - .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), - collectedWarningMessages)) - .filter(Either::isLeft) - .map(e -> e.left().value()) - .collect(toList()); + csarInfo.getCsar().entrySet().stream() + .filter(e -> Pattern.compile(VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()) + .matches()) + .map(e -> CsarUtils.validateNonMetaArtifact(e.getKey(), e.getValue(), + collectedWarningMessages)) + .filter(Either::isLeft) + .map(e -> e.left().value()) + .collect(toList()); Pattern englishNumbersAndUnderScoresOnly = Pattern.compile(CsarUtils.VALID_ENGLISH_ARTIFACT_NAME); for (CsarUtils.NonMetaArtifactInfo nonMetaArtifactInfo : artifactPathAndNameList) { if (!englishNumbersAndUnderScoresOnly.matcher(nonMetaArtifactInfo.getDisplayName()).matches()) { @@ -938,13 +969,13 @@ public class ServiceImportBusinessLogic{ } protected Either createGroupsOnResource(Service service, - Map groups) { + Map groups) { if (groups != null && !groups.isEmpty()) { List groupsAsList = updateGroupsMembersUsingResource(groups, service); serviceImportParseLogic.handleGroupsProperties(service, groups); serviceImportParseLogic.fillGroupsFinalFields(groupsAsList); Either, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(service, - groupsAsList, true); + groupsAsList, true); if (createGroups.isRight()) { return Either.right(createGroups.right().value()); } @@ -952,10 +983,10 @@ public class ServiceImportBusinessLogic{ return Either.left(service); } Either updatedResource = toscaOperationFacade - .getToscaElement(service.getUniqueId()); + .getToscaElement(service.getUniqueId()); if (updatedResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE); + componentsUtils.convertFromStorageResponse(updatedResource.right().value()), service, ComponentTypeEnum.SERVICE); return Either.right(responseFormat); } return Either.left(updatedResource.left().value()); @@ -977,7 +1008,7 @@ public class ServiceImportBusinessLogic{ Map members = groupDefinition.getMembers(); if (members != null) { serviceImportParseLogic - .updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members); + .updateGroupMembers(groups, updatedGroupDefinition, component, componentInstances, groupName, members); } result.add(updatedGroupDefinition); } @@ -987,18 +1018,18 @@ public class ServiceImportBusinessLogic{ protected Resource createRIAndRelationsFromYaml(String yamlName, Resource resource, - Map uploadComponentInstanceInfoMap, - String topologyTemplateYaml, List nodeTypesNewCreatedArtifacts, - Map nodeTypesInfo, CsarInfo csarInfo, - Map>> nodeTypesArtifactsToCreate, - String nodeName) { + Map uploadComponentInstanceInfoMap, + String topologyTemplateYaml, List nodeTypesNewCreatedArtifacts, + Map nodeTypesInfo, CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + String nodeName) { try { log.debug("************* Going to create all nodes {}", yamlName); handleNodeTypes(yamlName, resource, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, nodeName); + nodeTypesInfo, csarInfo, nodeName); log.debug("************* Going to create all resource instances {}", yamlName); resource = createResourceInstances(yamlName, resource, - uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes()); + uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes()); log.debug("************* Finished to create all resource instances {}", yamlName); resource = createResourceInstancesRelations(csarInfo.getModifier(), yamlName, resource, uploadComponentInstanceInfoMap); log.debug("************* Going to create positions {}", yamlName); @@ -1011,13 +1042,16 @@ public class ServiceImportBusinessLogic{ } protected Resource createResourceInstancesRelations(User user, String yamlName, Resource resource, - Map uploadResInstancesMap) { + Map uploadResInstancesMap) { log.debug("#createResourceInstancesRelations - Going to create relations "); List componentInstancesList = resource.getComponentInstances(); if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)) && - resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances - log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", resource.getUniqueId(), yamlName); - BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", BeEcompErrorManager.ErrorSeverity.ERROR); + resource.getResourceType() != ResourceTypeEnum.PNF)) { // PNF can have no resource instances + log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", + resource.getUniqueId(), yamlName); + BeEcompErrorManager.getInstance() + .logInternalDataError("createResourceInstancesRelations", "No instances found in a resource or nn yaml template. ", + BeEcompErrorManager.ErrorSeverity.ERROR); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName)); } Map> instProperties = new HashMap<>(); @@ -1025,7 +1059,7 @@ public class ServiceImportBusinessLogic{ Map>> instRequirements = new HashMap<>(); Map> instDeploymentArtifacts = new HashMap<>(); Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); Map originCompMap = new HashMap<>(); List relations = new ArrayList<>(); Map> instInputs = new HashMap<>(); @@ -1035,27 +1069,27 @@ public class ServiceImportBusinessLogic{ if (allDataTypes.isRight()) { JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", - "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); + "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName)); + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName)); } Resource finalResource = resource; uploadResInstancesMap - .values() - .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, - instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, - instArtifacts, instAttributes, originCompMap, instInputs, i)); + .values() + .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, + instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, + instArtifacts, instAttributes, originCompMap, instInputs, i)); serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties); serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, resource, instInputs); serviceImportParseLogic - .associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); + .associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); serviceImportParseLogic.associateArtifactsToInstances(yamlName, resource, instArtifacts); serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements); serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes); resource = serviceImportParseLogic.getResourceAfterCreateRelations(resource); serviceImportParseLogic - .addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations); + .addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, relations); serviceImportParseLogic.associateResourceInstances(yamlName, resource, relations); handleSubstitutionMappings(resource, uploadResInstancesMap); log.debug("************* in create relations, getResource start"); @@ -1063,22 +1097,26 @@ public class ServiceImportBusinessLogic{ log.debug("************* in create relations, getResource end"); if (eitherGetResource.isRight()) { throw new ComponentException(componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource)); + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource)); } return eitherGetResource.left().value(); } - protected void processProperty(Resource resource, ComponentInstance currentCompInstance, Map allDataTypes, Map currPropertiesMap, List instPropList, List propertyList) { + protected void processProperty(Resource resource, ComponentInstance currentCompInstance, Map allDataTypes, + Map currPropertiesMap, List instPropList, + List propertyList) { UploadPropInfo propertyInfo = propertyList.get(0); String propName = propertyInfo.getName(); if (!currPropertiesMap.containsKey(propName)) { throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - propName)); + propName)); } processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, resource.getInputs()); } - private void processProperty(Map allDataTypes, Map currPropertiesMap, List instPropList, UploadPropInfo propertyInfo, String propName, List inputs2) { + private void processProperty(Map allDataTypes, Map currPropertiesMap, + List instPropList, UploadPropInfo propertyInfo, String propName, + List inputs2) { InputDefinition curPropertyDef = currPropertiesMap.get(propName); ComponentInstanceInput property = null; @@ -1090,10 +1128,10 @@ public class ServiceImportBusinessLogic{ isValidate = getInputs == null || getInputs.isEmpty(); if (isValidate) { value = getPropertyJsonStringValue(propertyInfo.getValue(), - curPropertyDef.getType()); + curPropertyDef.getType()); } else { value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); } } property = new ComponentInstanceInput(curPropertyDef, value, null); @@ -1109,7 +1147,7 @@ public class ServiceImportBusinessLogic{ } Optional optional = inputs.stream() - .filter(p -> p.getName().equals(getInput.getInputName())).findAny(); + .filter(p -> p.getName().equals(getInput.getInputName())).findAny(); if (!optional.isPresent()) { throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); } @@ -1131,22 +1169,22 @@ public class ServiceImportBusinessLogic{ Either getResourceRes = toscaOperationFacade.getToscaFullElement(resource.getUniqueId()); if (getResourceRes.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); + componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); throw new ComponentException(responseFormat); } getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), - uploadResInstancesMap); + uploadResInstancesMap); if (getResourceRes.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); + componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), resource); throw new ComponentException(responseFormat); } } } protected Resource createResourceInstances(String yamlName, Resource resource, - Map uploadResInstancesMap, - Map nodeNamespaceMap) { + Map uploadResInstancesMap, + Map nodeNamespaceMap) { Either eitherResource = null; log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); if (MapUtils.isEmpty(uploadResInstancesMap) && resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances @@ -1159,18 +1197,18 @@ public class ServiceImportBusinessLogic{ } Map resourcesInstancesMap = new HashMap<>(); uploadResInstancesMap - .values() - .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap)); + .values() + .forEach(i -> createAndAddResourceInstance(i, yamlName, resource, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap)); if (MapUtils.isNotEmpty(resourcesInstancesMap)) { try { toscaOperationFacade.associateComponentInstancesToComponent(resource, - resourcesInstancesMap, false, false); + resourcesInstancesMap, false, false); } catch (StorageException exp) { if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) { log.debug("Failed to add component instances to container component {}", resource.getName()); ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus())); + .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus())); eitherResource = Either.right(responseFormat); throw new ByResponseFormatComponentException(eitherResource.right().value()); } @@ -1178,181 +1216,190 @@ public class ServiceImportBusinessLogic{ } log.debug("*************Going to get resource {}", resource.getUniqueId()); Either eitherGetResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter()); + .getToscaElement(resource.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter()); log.debug("*************finished to get resource {}", resource.getUniqueId()); if (eitherGetResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), resource); throw new ComponentException(responseFormat); } if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances()) && - resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances + resource.getResourceType() != ResourceTypeEnum.PNF) { // PNF can have no resource instances log.debug("Error when create resource instance from csar. ComponentInstances list empty"); BeEcompErrorManager.getInstance().logBeDaoSystemError( - "Error when create resource instance from csar. ComponentInstances list empty"); + "Error when create resource instance from csar. ComponentInstances list empty"); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); } return eitherGetResource.left().value(); } protected void handleNodeTypes(String yamlName, Resource resource, - String topologyTemplateYaml, boolean needLock, - Map>> nodeTypesArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, - CsarInfo csarInfo, String nodeName) { + String topologyTemplateYaml, boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, + CsarInfo csarInfo, String nodeName) { try { for (Map.Entry nodeTypeEntry : nodeTypesInfo.entrySet()) { if (nodeTypeEntry.getValue().isNested()) { handleNestedVfc(resource, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, nodeTypeEntry.getKey()); + nodeTypesInfo, csarInfo, nodeTypeEntry.getKey()); log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); } } Map mappedToscaTemplate = null; if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) - && nodeTypesInfo.containsKey(nodeName)) { + && nodeTypesInfo.containsKey(nodeName)) { mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); } if (MapUtils.isEmpty(mappedToscaTemplate)) { mappedToscaTemplate = (Map) new Yaml().load(topologyTemplateYaml); } createResourcesFromYamlNodeTypesList(yamlName, resource, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); + nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); } catch (ComponentException e) { ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() - : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); + : componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()); componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); throw e; } catch (StorageException e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); throw e; - }catch (Exception e){ + } catch (Exception e) { log.debug("Exception occured when handleNodeTypes, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } } - protected Resource handleNestedVfc(Service service, Map>> nodesArtifactsToHandle, + protected Resource handleNestedVfc(Service service, + Map>> nodesArtifactsToHandle, List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, String nodeName) { try { String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); Map nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, - nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); + nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); log.debug("************* Finished to create node types from yaml {}", yamlName); if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { log.debug("************* Going to handle complex VFC from yaml {}", yamlName); - Resource resource = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, - csarInfo, nodeName, yamlName); - return resource; + return handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName); } return new Resource(); - } catch (Exception e) { + } catch (Exception e) { log.debug("Exception occured when handleNestedVFc, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } } - protected Resource handleNestedVfc(Resource resource, Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - String nodeName) { + protected Resource handleNestedVfc(Resource resource, + Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName) { String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); Map nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); log.debug("************* Going to create node types from yaml {}", yamlName); createResourcesFromYamlNodeTypesList(yamlName, resource, nestedVfcJsonMap, false, - nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); + nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { log.debug("************* Going to handle complex VFC from yaml {}", yamlName); resource = handleComplexVfc(resource, nodesArtifactsToHandle, createdArtifacts, nodesInfo, - csarInfo, nodeName, yamlName); + csarInfo, nodeName, yamlName); } return resource; } - protected Resource handleComplexVfc(Resource resource, Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - String nodeName, String yamlName) { + protected Resource handleComplexVfc(Resource resource, + Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName) { Resource oldComplexVfc = null; Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(resource, csarInfo, nodeName, nodesInfo); Either oldComplexVfcRes = toscaOperationFacade - .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); + .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName( - serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), - nodeName).getRight()); + serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), + nodeName).getRight()); } if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { throw new ComponentException(ActionStatus.GENERAL_ERROR); } else if (oldComplexVfcRes.isLeft()) { log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); Either eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate( - oldComplexVfcRes.left().value(), newComplexVfc, - ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); + oldComplexVfcRes.left().value(), newComplexVfc, + ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); if (eitherValidation.isLeft()) { oldComplexVfc = oldComplexVfcRes.left().value(); } } newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, - oldComplexVfc, newComplexVfc); + oldComplexVfc, newComplexVfc); csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction( - CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); + CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); final Resource result = serviceImportParseLogic - .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, - true); + .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, + true); csarInfo.getCreatedNodes().put(nodeName, result); csarInfo.removeNodeFromQueue(); return result; } - public Map createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map mappedToscaTemplate, boolean needLock, - Map>> nodeTypesArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, + public Map createResourcesFromYamlNodeTypesList(String yamlName, Resource resource, Map mappedToscaTemplate, + boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, + Map nodeTypesInfo, CsarInfo csarInfo) { Either toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, - TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); + TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); if (toscaVersion.isRight()) { throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE); } Map mapToConvert = new HashMap<>(); mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value()); Map nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate); - createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes); + createNodeTypes(yamlName, resource, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, + nodeTypes); return csarInfo.getCreatedNodes(); } - protected void createNodeTypes(String yamlName, Resource resource, boolean needLock, Map>> nodeTypesArtifactsToHandle, List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, CsarInfo csarInfo, Map mapToConvert, Map nodeTypes) { + protected void createNodeTypes(String yamlName, Resource resource, boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, CsarInfo csarInfo, + Map mapToConvert, Map nodeTypes) { Iterator> nodesNameValueIter = nodeTypes.entrySet().iterator(); Resource vfcCreated = null; while (nodesNameValueIter.hasNext()) { Map.Entry nodeType = nodesNameValueIter.next(); Map> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null - || nodeTypesArtifactsToHandle.isEmpty() ? null - : nodeTypesArtifactsToHandle.get(nodeType.getKey()); + || nodeTypesArtifactsToHandle.isEmpty() ? null + : nodeTypesArtifactsToHandle.get(nodeType.getKey()); if (nodeTypesInfo.containsKey(nodeType.getKey())) { log.trace("************* Going to handle nested vfc {}", nodeType.getKey()); vfcCreated = handleNestedVfc(resource, - nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, - nodeType.getKey()); + nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeType.getKey()); log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); } else if (csarInfo.getCreatedNodesToscaResourceNames() != null - && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) { + && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) { log.trace("************* Going to create node {}", nodeType.getKey()); - ImmutablePair resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, - resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, - csarInfo, true); + ImmutablePair resourceCreated = createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), + mapToConvert, + resource, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, + csarInfo, true); log.debug("************* Finished to create node {}", nodeType.getKey()); vfcCreated = resourceCreated.getLeft(); csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), - vfcCreated.getToscaResourceName()); + vfcCreated.getToscaResourceName()); } if (vfcCreated != null) { csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); @@ -1362,30 +1409,31 @@ public class ServiceImportBusinessLogic{ } protected ImmutablePair createNodeTypeResourceFromYaml( - String yamlName, Map.Entry nodeNameValue, User user, Map mapToConvert, - Resource resourceVf, boolean needLock, - Map> nodeTypeArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, - boolean isNested) { + String yamlName, Map.Entry nodeNameValue, User user, Map mapToConvert, + Resource resourceVf, boolean needLock, + Map> nodeTypeArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, boolean forceCertificationAllowed, CsarInfo csarInfo, + boolean isNested) { UploadResourceInfo resourceMetaData = serviceImportParseLogic - .fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); + .fillResourceMetadata(yamlName, resourceVf, nodeNameValue.getKey(), user); String singleVfcYaml = serviceImportParseLogic.buildNodeTypeYaml(nodeNameValue, mapToConvert, - resourceMetaData.getResourceType(), csarInfo); + resourceMetaData.getResourceType(), csarInfo); user = serviceBusinessLogic.validateUser(user, "CheckIn Resource", resourceVf, AuditingActionEnum.CHECKIN_RESOURCE, true); return serviceImportParseLogic.createResourceFromNodeType(singleVfcYaml, resourceMetaData, user, true, needLock, - nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, - nodeNameValue.getKey(), isNested); + nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, forceCertificationAllowed, csarInfo, + nodeNameValue.getKey(), isNested); } protected Service createRIAndRelationsFromYaml(String yamlName, Service service, - Map uploadComponentInstanceInfoMap, - String topologyTemplateYaml, List nodeTypesNewCreatedArtifacts, - Map nodeTypesInfo, CsarInfo csarInfo, - Map>> nodeTypesArtifactsToCreate, - String nodeName) { + Map uploadComponentInstanceInfoMap, + String topologyTemplateYaml, List nodeTypesNewCreatedArtifacts, + Map nodeTypesInfo, CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + String nodeName) { log.debug("************* Going to create all nodes {}", yamlName); - handleServiceNodeTypes(yamlName, service, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, nodeName); + handleServiceNodeTypes(yamlName, service, topologyTemplateYaml, false, nodeTypesArtifactsToCreate, nodeTypesNewCreatedArtifacts, + nodeTypesInfo, csarInfo, nodeName); log.debug("************* Going to create all resource instances {}", yamlName); service = createServiceInstances(yamlName, service, uploadComponentInstanceInfoMap, csarInfo.getCreatedNodes()); log.debug("************* Going to create all relations {}", yamlName); @@ -1397,12 +1445,15 @@ public class ServiceImportBusinessLogic{ } protected Service createServiceInstancesRelations(User user, String yamlName, Service service, - Map uploadResInstancesMap) { + Map uploadResInstancesMap) { log.debug("#createResourceInstancesRelations - Going to create relations "); List componentInstancesList = service.getComponentInstances(); if (((MapUtils.isEmpty(uploadResInstancesMap) || CollectionUtils.isEmpty(componentInstancesList)))) { // PNF can have no resource instances - log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", service.getUniqueId(), yamlName); - BeEcompErrorManager.getInstance().logInternalDataError("createResourceInstancesRelations", "No instances found in a component or nn yaml template. ", BeEcompErrorManager.ErrorSeverity.ERROR); + log.debug("#createResourceInstancesRelations - No instances found in the resource {} is empty, yaml template file name {}, ", + service.getUniqueId(), yamlName); + BeEcompErrorManager.getInstance() + .logInternalDataError("createResourceInstancesRelations", "No instances found in a component or nn yaml template. ", + BeEcompErrorManager.ErrorSeverity.ERROR); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName)); } Map> instProperties = new HashMap<>(); @@ -1410,7 +1461,7 @@ public class ServiceImportBusinessLogic{ Map>> instRequirements = new HashMap<>(); Map> instDeploymentArtifacts = new HashMap<>(); Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); Map originCompMap = new HashMap<>(); List relations = new ArrayList<>(); Map> instInputs = new HashMap<>(); @@ -1420,23 +1471,23 @@ public class ServiceImportBusinessLogic{ if (allDataTypes.isRight()) { JanusGraphOperationStatus status = allDataTypes.right().value(); BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", - "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); + "Failed to update property value on instance. Status is " + status, BeEcompErrorManager.ErrorSeverity.ERROR); throw new ComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( - DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName)); + DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)), yamlName)); } Service finalResource = service; uploadResInstancesMap - .values() - .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, - instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, - instArtifacts, instAttributes, originCompMap, instInputs, i)); + .values() + .forEach(i -> processComponentInstance(yamlName, finalResource, componentInstancesList, allDataTypes, + instProperties, instCapabilities, instRequirements, instDeploymentArtifacts, + instArtifacts, instAttributes, originCompMap, instInputs, i)); serviceImportParseLogic.associateComponentInstancePropertiesToComponent(yamlName, service, instProperties); serviceImportParseLogic.associateComponentInstanceInputsToComponent(yamlName, service, instInputs); serviceImportParseLogic.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts); serviceImportParseLogic.associateArtifactsToInstances(yamlName, service, instArtifacts); serviceImportParseLogic.associateOrAddCalculatedCapReq(yamlName, service, instCapabilities, instRequirements); log.debug("enter createServiceInstancesRelations test,instRequirements:{},instCapabilities:{}", - instRequirements, instCapabilities); + instRequirements, instCapabilities); serviceImportParseLogic.associateInstAttributeToComponentToInstances(yamlName, service, instAttributes); ToscaElement serviceTemplate = ModelConverter.convertToToscaElement(service); Map capabilities = serviceTemplate.getCapabilities(); @@ -1454,7 +1505,7 @@ public class ServiceImportBusinessLogic{ log.debug("************* in create relations, getResource end"); if (eitherGetResource.isRight()) { throw new ComponentException(componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, service.getComponentType())); + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, service.getComponentType())); } return eitherGetResource.left().value(); } @@ -1467,22 +1518,22 @@ public class ServiceImportBusinessLogic{ Map>> instRequirements, Map> instDeploymentArtifacts, Map> instArtifacts, - Map> instAttributes, + Map> instAttributes, Map originCompMap, Map> instInputs, UploadComponentInstanceInfo uploadComponentInstanceInfo) { log.debug("enter ServiceImportBusinessLogic processComponentInstance"); Optional currentCompInstanceOpt = componentInstancesList.stream() - .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())) - .findFirst(); + .filter(i -> i.getName().equals(uploadComponentInstanceInfo.getName())) + .findFirst(); if (!currentCompInstanceOpt.isPresent()) { log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), - component.getUniqueId()); + component.getUniqueId()); BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, - component.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); + COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, + component.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); throw new ComponentException(responseFormat); } ComponentInstance currentCompInstance = currentCompInstanceOpt.get(); @@ -1494,7 +1545,7 @@ public class ServiceImportBusinessLogic{ } if (MapUtils.isNotEmpty(originResource.getCapabilities())) { processComponentInstanceCapabilities(allDataTypes, instCapabilties, uploadComponentInstanceInfo, - currentCompInstance, originResource); + currentCompInstance, originResource); } if (originResource.getDeploymentArtifacts() != null && !originResource.getDeploymentArtifacts().isEmpty()) { instDeploymentArtifacts.put(resourceInstanceId, originResource.getDeploymentArtifacts()); @@ -1507,13 +1558,13 @@ public class ServiceImportBusinessLogic{ } if (originResource.getResourceType() != ResourceTypeEnum.VF) { ResponseFormat addPropertiesValueToRiRes = addPropertyValuesToRi(uploadComponentInstanceInfo, component, - originResource, currentCompInstance, instProperties, allDataTypes.left().value()); + originResource, currentCompInstance, instProperties, allDataTypes.left().value()); if (addPropertiesValueToRiRes.getStatus() != 200) { throw new ComponentException(addPropertiesValueToRiRes); } } else { addInputsValuesToRi(uploadComponentInstanceInfo, component, - originResource, currentCompInstance, instInputs, allDataTypes.left().value()); + originResource, currentCompInstance, instInputs, allDataTypes.left().value()); } } @@ -1544,22 +1595,25 @@ public class ServiceImportBusinessLogic{ } } - protected void processProperty(Component component, ComponentInstance currentCompInstance, Map allDataTypes, Map currPropertiesMap, List instPropList, List propertyList) { + protected void processProperty(Component component, ComponentInstance currentCompInstance, Map allDataTypes, + Map currPropertiesMap, List instPropList, + List propertyList) { UploadPropInfo propertyInfo = propertyList.get(0); String propName = propertyInfo.getName(); if (!currPropertiesMap.containsKey(propName)) { log.debug("failed to find property {} ", propName); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - propName)); + propName)); } processProperty(allDataTypes, currPropertiesMap, instPropList, propertyInfo, propName, component.getInputs()); } - protected void processGetInput(List getInputValues, List inputs, GetInputValueDataDefinition getInputIndex) { + protected void processGetInput(List getInputValues, List inputs, + GetInputValueDataDefinition getInputIndex) { Optional optional; if (getInputIndex != null) { optional = inputs.stream().filter(p -> p.getName().equals(getInputIndex.getInputName())) - .findAny(); + .findAny(); if (!optional.isPresent()) { log.debug("Failed to find input {} ", getInputIndex.getInputName()); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT)); @@ -1571,8 +1625,9 @@ public class ServiceImportBusinessLogic{ } protected ResponseFormat addPropertyValuesToRi(UploadComponentInstanceInfo uploadComponentInstanceInfo, - Component component, Resource originResource, ComponentInstance currentCompInstance, - Map> instProperties, Map allDataTypes) { + Component component, Resource originResource, ComponentInstance currentCompInstance, + Map> instProperties, + Map allDataTypes) { Map> propMap = uploadComponentInstanceInfo.getProperties(); Map currPropertiesMap = new HashMap<>(); @@ -1598,7 +1653,7 @@ public class ServiceImportBusinessLogic{ if (!currPropertiesMap.containsKey(propName)) { log.debug("failed to find property {} ", propName); return componentsUtils.getResponseFormat(ActionStatus.PROPERTY_NOT_FOUND, - propName); + propName); } PropertyDefinition curPropertyDef = currPropertiesMap.get(propName); ComponentInstanceProperty property = null; @@ -1611,10 +1666,10 @@ public class ServiceImportBusinessLogic{ isValidate = getInputs == null || getInputs.isEmpty(); if (isValidate) { value = getPropertyJsonStringValue(propertyInfo.getValue(), - curPropertyDef.getType()); + curPropertyDef.getType()); } else { value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); } } property = new ComponentInstanceProperty(curPropertyDef, value, null); @@ -1629,9 +1684,9 @@ public class ServiceImportBusinessLogic{ if (inputs == null || inputs.isEmpty()) { log.debug("Failed to add property {} to instance. Inputs list is empty ", property); serviceBusinessLogic.rollbackWithException(ActionStatus.INPUTS_NOT_FOUND, property.getGetInputValues() - .stream() - .map(GetInputValueDataDefinition::getInputName) - .collect(toList()).toString()); + .stream() + .map(GetInputValueDataDefinition::getInputName) + .collect(toList()).toString()); } InputDefinition input = serviceImportParseLogic.findInputByName(inputs, getInput); getInput.setInputId(input.getUniqueId()); @@ -1659,16 +1714,19 @@ public class ServiceImportBusinessLogic{ return componentsUtils.getResponseFormat(ActionStatus.OK); } - protected void processComponentInstanceCapabilities(Either, JanusGraphOperationStatus> allDataTypes, Map>> instCapabilties, UploadComponentInstanceInfo uploadComponentInstanceInfo, ComponentInstance currentCompInstance, Resource originResource) { + protected void processComponentInstanceCapabilities(Either, JanusGraphOperationStatus> allDataTypes, + Map>> instCapabilties, + UploadComponentInstanceInfo uploadComponentInstanceInfo, + ComponentInstance currentCompInstance, Resource originResource) { log.debug("enter processComponentInstanceCapabilities"); Map> originCapabilities; if (MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities())) { originCapabilities = new HashMap<>(); Map> newPropertiesMap = new HashMap<>(); originResource.getCapabilities().forEach((k, v) -> serviceImportParseLogic - .addCapabilities(originCapabilities, k, v)); + .addCapabilities(originCapabilities, k, v)); uploadComponentInstanceInfo.getCapabilities().values().forEach(l -> serviceImportParseLogic - .addCapabilitiesProperties(newPropertiesMap, l)); + .addCapabilitiesProperties(newPropertiesMap, l)); updateCapabilityPropertiesValues(allDataTypes, originCapabilities, newPropertiesMap); } else { originCapabilities = originResource.getCapabilities(); @@ -1676,20 +1734,22 @@ public class ServiceImportBusinessLogic{ instCapabilties.put(currentCompInstance, originCapabilities); } - protected void updateCapabilityPropertiesValues(Either, JanusGraphOperationStatus> allDataTypes, Map> originCapabilities, Map> newPropertiesMap) { + protected void updateCapabilityPropertiesValues(Either, JanusGraphOperationStatus> allDataTypes, + Map> originCapabilities, + Map> newPropertiesMap) { originCapabilities.values().stream() - .flatMap(Collection::stream) - .filter(c -> newPropertiesMap.containsKey(c.getName())) - .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value())); + .flatMap(Collection::stream) + .filter(c -> newPropertiesMap.containsKey(c.getName())) + .forEach(c -> updatePropertyValues(c.getProperties(), newPropertiesMap.get(c.getName()), allDataTypes.left().value())); } protected void updatePropertyValues(List properties, Map newProperties, - Map allDataTypes) { + Map allDataTypes) { properties.forEach(p -> updatePropertyValue(p, newProperties.get(p.getName()), allDataTypes)); } protected String updatePropertyValue(ComponentInstanceProperty property, UploadPropInfo propertyInfo, - Map allDataTypes) { + Map allDataTypes) { String value = null; List getInputs = null; boolean isValidate = true; @@ -1700,7 +1760,7 @@ public class ServiceImportBusinessLogic{ value = getPropertyJsonStringValue(propertyInfo.getValue(), property.getType()); } else { value = getPropertyJsonStringValue(propertyInfo.getValue(), - TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); + TypeUtils.ToscaTagNamesEnum.GET_INPUT.getElementName()); } } property.setValue(value); @@ -1712,10 +1772,10 @@ public class ServiceImportBusinessLogic{ log.debug("after enter ServiceImportBusinessLogic processComponentInstance, enter getOriginResource"); if (!originCompMap.containsKey(currentCompInstance.getComponentUid())) { Either getOriginResourceRes = toscaOperationFacade - .getToscaFullElement(currentCompInstance.getComponentUid()); + .getToscaFullElement(currentCompInstance.getComponentUid()); if (getOriginResourceRes.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName); + componentsUtils.convertFromStorageResponse(getOriginResourceRes.right().value()), yamlName); throw new ComponentException(responseFormat); } originResource = getOriginResourceRes.left().value(); @@ -1731,37 +1791,37 @@ public class ServiceImportBusinessLogic{ Either getResourceRes = toscaOperationFacade.getToscaFullElement(service.getUniqueId()); if (getResourceRes.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE); + componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE); throw new ComponentException(responseFormat); } getResourceRes = updateCalculatedCapReqWithSubstitutionMappings(getResourceRes.left().value(), - uploadResInstancesMap); + uploadResInstancesMap); if (getResourceRes.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE); + componentsUtils.convertFromStorageResponse(getResourceRes.right().value()), service, ComponentTypeEnum.SERVICE); throw new ComponentException(responseFormat); } } } protected Either updateCalculatedCapReqWithSubstitutionMappings(Resource resource, - Map uploadResInstancesMap) { + Map uploadResInstancesMap) { Either updateRes = null; Map>> updatedInstCapabilities = new HashMap<>(); Map>> updatedInstRequirements = new HashMap<>(); StorageOperationStatus status = toscaOperationFacade - .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId()); + .deleteAllCalculatedCapabilitiesRequirements(resource.getUniqueId()); if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { log.debug( - "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", - resource.getUniqueId(), status); + "Failed to delete all calculated capabilities and requirements of resource {} upon update. Status is {}", + resource.getUniqueId(), status); updateRes = Either.right(status); } if (updateRes == null) { fillUpdatedInstCapabilitiesRequirements(resource.getComponentInstances(), uploadResInstancesMap, - updatedInstCapabilities, updatedInstRequirements); + updatedInstCapabilities, updatedInstRequirements); status = toscaOperationFacade.associateOrAddCalculatedCapReq(updatedInstCapabilities, updatedInstRequirements, - resource); + resource); if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) { updateRes = Either.right(status); } @@ -1773,34 +1833,34 @@ public class ServiceImportBusinessLogic{ } protected void fillUpdatedInstCapabilitiesRequirements(List componentInstances, - Map uploadResInstancesMap, - Map>> updatedInstCapabilities, - Map>> updatedInstRequirements) { + Map uploadResInstancesMap, + Map>> updatedInstCapabilities, + Map>> updatedInstRequirements) { componentInstances.stream().forEach(i -> { fillUpdatedInstCapabilities(updatedInstCapabilities, i, - uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate()); + uploadResInstancesMap.get(i.getName()).getCapabilitiesNamesToUpdate()); fillUpdatedInstRequirements(updatedInstRequirements, i, - uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate()); + uploadResInstancesMap.get(i.getName()).getRequirementsNamesToUpdate()); }); } protected void fillUpdatedInstCapabilities( - Map>> updatedInstCapabilties, - ComponentInstance instance, Map capabilitiesNamesToUpdate) { + Map>> updatedInstCapabilties, + ComponentInstance instance, Map capabilitiesNamesToUpdate) { Map> updatedCapabilities = new HashMap<>(); Set updatedCapNames = new HashSet<>(); if (MapUtils.isNotEmpty(capabilitiesNamesToUpdate)) { for (Map.Entry> requirements : instance.getCapabilities().entrySet()) { updatedCapabilities.put(requirements.getKey(), - requirements.getValue().stream() - .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) - && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName()))) - .map(c -> { - c.setParentName(c.getName()); - c.setName(capabilitiesNamesToUpdate.get(c.getName())); - updatedCapNames.add(c.getName()); - return c; - }).collect(toList())); + requirements.getValue().stream() + .filter(c -> capabilitiesNamesToUpdate.containsKey(c.getName()) + && !updatedCapNames.contains(capabilitiesNamesToUpdate.get(c.getName()))) + .map(c -> { + c.setParentName(c.getName()); + c.setName(capabilitiesNamesToUpdate.get(c.getName())); + updatedCapNames.add(c.getName()); + return c; + }).collect(toList())); } } if (MapUtils.isNotEmpty(updatedCapabilities)) { @@ -1809,22 +1869,22 @@ public class ServiceImportBusinessLogic{ } protected void fillUpdatedInstRequirements( - Map>> updatedInstRequirements, - ComponentInstance instance, Map requirementsNamesToUpdate) { + Map>> updatedInstRequirements, + ComponentInstance instance, Map requirementsNamesToUpdate) { Map> updatedRequirements = new HashMap<>(); Set updatedReqNames = new HashSet<>(); if (MapUtils.isNotEmpty(requirementsNamesToUpdate)) { for (Map.Entry> requirements : instance.getRequirements().entrySet()) { updatedRequirements.put(requirements.getKey(), - requirements.getValue().stream() - .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) - && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName()))) - .map(r -> { - r.setParentName(r.getName()); - r.setName(requirementsNamesToUpdate.get(r.getName())); - updatedReqNames.add(r.getName()); - return r; - }).collect(toList())); + requirements.getValue().stream() + .filter(r -> requirementsNamesToUpdate.containsKey(r.getName()) + && !updatedReqNames.contains(requirementsNamesToUpdate.get(r.getName()))) + .map(r -> { + r.setParentName(r.getName()); + r.setName(requirementsNamesToUpdate.get(r.getName())); + updatedReqNames.add(r.getName()); + return r; + }).collect(toList())); } } if (MapUtils.isNotEmpty(updatedRequirements)) { @@ -1832,7 +1892,8 @@ public class ServiceImportBusinessLogic{ } } - protected void addRelationsToRI(String yamlName, Service service, Map uploadResInstancesMap, List componentInstancesList, List relations) { + protected void addRelationsToRI(String yamlName, Service service, Map uploadResInstancesMap, + List componentInstancesList, List relations) { for (Map.Entry entry : uploadResInstancesMap.entrySet()) { UploadComponentInstanceInfo uploadComponentInstanceInfo = entry.getValue(); ComponentInstance currentCompInstance = null; @@ -1844,12 +1905,12 @@ public class ServiceImportBusinessLogic{ } if (currentCompInstance == null) { log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, uploadComponentInstanceInfo.getName(), - service.getUniqueId()); + service.getUniqueId()); BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, - service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); + COMPONENT_INSTANCE_WITH_NAME + uploadComponentInstanceInfo.getName() + IN_RESOURCE, + service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); ResponseFormat responseFormat = componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); throw new ComponentException(responseFormat); } @@ -1861,7 +1922,7 @@ public class ServiceImportBusinessLogic{ } protected ResponseFormat addRelationToRI(String yamlName, Service service, - UploadComponentInstanceInfo nodesInfoValue, List relations) { + UploadComponentInstanceInfo nodesInfoValue, List relations) { List componentInstancesList = service.getComponentInstances(); ComponentInstance currentCompInstance = null; for (ComponentInstance compInstance : componentInstancesList) { @@ -1872,12 +1933,12 @@ public class ServiceImportBusinessLogic{ } if (currentCompInstance == null) { log.debug(COMPONENT_INSTANCE_WITH_NAME_IN_RESOURCE, nodesInfoValue.getName(), - service.getUniqueId()); + service.getUniqueId()); BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, - service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); + COMPONENT_INSTANCE_WITH_NAME + nodesInfoValue.getName() + IN_RESOURCE, + service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); return componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, - yamlName); + yamlName); } String resourceInstanceId = currentCompInstance.getUniqueId(); Map> regMap = nodesInfoValue.getRequirements(); @@ -1894,17 +1955,17 @@ public class ServiceImportBusinessLogic{ regCapRelDef.setFromNode(resourceInstanceId); log.debug("try to find available requirement {} ", regName); Either eitherReqStatus = serviceImportParseLogic.findAviableRequiremen(regName, - yamlName, nodesInfoValue, currentCompInstance, - uploadRegInfo.getCapabilityName()); + yamlName, nodesInfoValue, currentCompInstance, + uploadRegInfo.getCapabilityName()); if (eitherReqStatus.isRight()) { log.debug("failed to find available requirement {} status is {}", regName, - eitherReqStatus.right().value()); + eitherReqStatus.right().value()); return eitherReqStatus.right().value(); } RequirementDefinition validReq = eitherReqStatus.left().value(); List reqAndRelationshipPairList = regCapRelDef - .getRelationships(); + .getRelationships(); if (reqAndRelationshipPairList == null) { reqAndRelationshipPairList = new ArrayList<>(); } @@ -1925,27 +1986,27 @@ public class ServiceImportBusinessLogic{ } if (currentCapCompInstance == null) { log.debug("The component instance with name {} not found on resource {} ", - uploadRegInfo.getNode(), service.getUniqueId()); + uploadRegInfo.getNode(), service.getUniqueId()); BeEcompErrorManager.getInstance().logInternalDataError( - COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, - service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); + COMPONENT_INSTANCE_WITH_NAME + uploadRegInfo.getNode() + IN_RESOURCE, + service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); return componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } regCapRelDef.setToNode(currentCapCompInstance.getUniqueId()); log.debug("try to find aviable Capability req name is {} ", validReq.getName()); CapabilityDefinition aviableCapForRel = serviceImportParseLogic.findAvailableCapabilityByTypeOrName(validReq, - currentCapCompInstance, uploadRegInfo); + currentCapCompInstance, uploadRegInfo); reqAndRelationshipPair.setCapability(aviableCapForRel.getName()); reqAndRelationshipPair.setCapabilityUid(aviableCapForRel.getUniqueId()); reqAndRelationshipPair.setCapabilityOwnerId(aviableCapForRel.getOwnerId()); if (aviableCapForRel == null) { BeEcompErrorManager.getInstance().logInternalDataError( - "aviable capability was not found. req name is " + validReq.getName() - + " component instance is " + currentCapCompInstance.getUniqueId(), - service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); + "aviable capability was not found. req name is " + validReq.getName() + + " component instance is " + currentCapCompInstance.getUniqueId(), + service.getUniqueId(), BeEcompErrorManager.ErrorSeverity.ERROR); return componentsUtils - .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); + .getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship(); capReqRel.setRelation(reqAndRelationshipPair); @@ -1961,7 +2022,7 @@ public class ServiceImportBusinessLogic{ protected Service getResourceAfterCreateRelations(Service service) { ComponentParametersView parametersView = serviceImportParseLogic.getComponentFilterAfterCreateRelations(); Either eitherGetResource = toscaOperationFacade - .getToscaElement(service.getUniqueId(), parametersView); + .getToscaElement(service.getUniqueId(), parametersView); if (eitherGetResource.isRight()) { serviceImportParseLogic.throwComponentExceptionByResource(eitherGetResource.right().value(), service); } @@ -1969,8 +2030,8 @@ public class ServiceImportBusinessLogic{ } protected Service createServiceInstances(String yamlName, Service service, - Map uploadResInstancesMap, - Map nodeNamespaceMap) { + Map uploadResInstancesMap, + Map nodeNamespaceMap) { Either eitherResource = null; log.debug("createResourceInstances is {} - going to create resource instanse from CSAR", yamlName); if (MapUtils.isEmpty(uploadResInstancesMap)) { // PNF can have no resource instances @@ -1983,50 +2044,51 @@ public class ServiceImportBusinessLogic{ } Map resourcesInstancesMap = new HashMap<>(); uploadResInstancesMap - .values() - .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap)); + .values() + .forEach(i -> createAndAddResourceInstance(i, yamlName, service, nodeNamespaceMap, existingNodeTypeMap, resourcesInstancesMap)); if (MapUtils.isNotEmpty(resourcesInstancesMap)) { try { toscaOperationFacade.associateComponentInstancesToComponent(service, - resourcesInstancesMap, false, false); + resourcesInstancesMap, false, false); } catch (StorageException exp) { if (exp.getStorageOperationStatus() != null && exp.getStorageOperationStatus() != StorageOperationStatus.OK) { log.debug("Failed to add component instances to container component {}", service.getName()); ResponseFormat responseFormat = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus())); + .getResponseFormat(componentsUtils.convertFromStorageResponse(exp.getStorageOperationStatus())); eitherResource = Either.right(responseFormat); throw new ComponentException(eitherResource.right().value()); } } } Either eitherGetResource = toscaOperationFacade - .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter()); + .getToscaElement(service.getUniqueId(), serviceImportParseLogic.getComponentWithInstancesFilter()); log.debug("*************finished to get resource {}", service.getUniqueId()); if (eitherGetResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByComponent( - componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, ComponentTypeEnum.SERVICE); + componentsUtils.convertFromStorageResponse(eitherGetResource.right().value()), service, ComponentTypeEnum.SERVICE); throw new ComponentException(responseFormat); } if (CollectionUtils.isEmpty(eitherGetResource.left().value().getComponentInstances())) { // PNF can have no resource instances log.debug("Error when create resource instance from csar. ComponentInstances list empty"); BeEcompErrorManager.getInstance().logBeDaoSystemError( - "Error when create resource instance from csar. ComponentInstances list empty"); + "Error when create resource instance from csar. ComponentInstances list empty"); throw new ComponentException(componentsUtils.getResponseFormat(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE)); } return eitherGetResource.left().value(); } protected void createAndAddResourceInstance(UploadComponentInstanceInfo uploadComponentInstanceInfo, String yamlName, - Component component, Map nodeNamespaceMap, Map existingnodeTypeMap, Map resourcesInstancesMap) { + Component component, Map nodeNamespaceMap, + Map existingnodeTypeMap, Map resourcesInstancesMap) { log.debug("*************Going to create resource instances {}", uploadComponentInstanceInfo.getName()); try { if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { uploadComponentInstanceInfo - .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); + .setType(nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()).getToscaResourceName()); } Resource refResource = validateResourceInstanceBeforeCreate(yamlName, uploadComponentInstanceInfo, - existingnodeTypeMap); + existingnodeTypeMap); ComponentInstance componentInstance = new ComponentInstance(); componentInstance.setComponentUid(refResource.getUniqueId()); @@ -2037,23 +2099,24 @@ public class ServiceImportBusinessLogic{ UploadNodeFilterInfo uploadNodeFilterInfo = uploadComponentInstanceInfo.getUploadNodeFilterInfo(); if (uploadNodeFilterInfo != null) { componentInstance.setNodeFilter(new CINodeFilterUtils().getNodeFilterDataDefinition(uploadNodeFilterInfo, - componentInstance.getUniqueId())); + componentInstance.getUniqueId())); } ComponentTypeEnum containerComponentType = component.getComponentType(); NodeTypeEnum containerNodeType = containerComponentType.getNodeType(); if (containerNodeType.equals(NodeTypeEnum.Resource) - && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) - && MapUtils.isNotEmpty(refResource.getCapabilities())) { + && MapUtils.isNotEmpty(uploadComponentInstanceInfo.getCapabilities()) + && MapUtils.isNotEmpty(refResource.getCapabilities())) { serviceImportParseLogic.setCapabilityNamesTypes(refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); - Map> validComponentInstanceCapabilities = serviceImportParseLogic.getValidComponentInstanceCapabilities( + Map> validComponentInstanceCapabilities = serviceImportParseLogic + .getValidComponentInstanceCapabilities( refResource.getUniqueId(), refResource.getCapabilities(), uploadComponentInstanceInfo.getCapabilities()); componentInstance.setCapabilities(validComponentInstanceCapabilities); } if (!existingnodeTypeMap.containsKey(uploadComponentInstanceInfo.getType())) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); throw new ComponentException(responseFormat); } Resource origResource = existingnodeTypeMap.get(uploadComponentInstanceInfo.getType()); @@ -2061,22 +2124,22 @@ public class ServiceImportBusinessLogic{ componentInstance.setIcon(origResource.getIcon()); resourcesInstancesMap.put(componentInstance, origResource); } catch (Exception e) { - throw new ComponentException(ActionStatus.GENERAL_ERROR,e.getMessage()); + throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage()); } } protected Resource validateResourceInstanceBeforeCreate(String yamlName, UploadComponentInstanceInfo uploadComponentInstanceInfo, - Map nodeNamespaceMap) { + Map nodeNamespaceMap) { Resource refResource; try { if (nodeNamespaceMap.containsKey(uploadComponentInstanceInfo.getType())) { refResource = nodeNamespaceMap.get(uploadComponentInstanceInfo.getType()); } else { Either findResourceEither = toscaOperationFacade - .getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType()); + .getLatestResourceByToscaResourceName(uploadComponentInstanceInfo.getType()); if (findResourceEither.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); + componentsUtils.convertFromStorageResponse(findResourceEither.right().value())); throw new ComponentException(responseFormat); } refResource = findResourceEither.left().value(); @@ -2085,49 +2148,49 @@ public class ServiceImportBusinessLogic{ String componentState = refResource.getComponentMetadataDefinition().getMetadataDataDefinition().getState(); if (componentState.equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) { ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ILLEGAL_COMPONENT_STATE, - refResource.getComponentType().getValue(), refResource.getName(), componentState); + refResource.getComponentType().getValue(), refResource.getName(), componentState); throw new ComponentException(responseFormat); } if (!ModelConverter.isAtomicComponent(refResource) && refResource.getResourceType() != ResourceTypeEnum.VF) { log.debug("validateResourceInstanceBeforeCreate - ref resource type is ", refResource.getResourceType()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_NODE_TEMPLATE, - yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); + yamlName, uploadComponentInstanceInfo.getName(), uploadComponentInstanceInfo.getType()); throw new ComponentException(responseFormat); } return refResource; } catch (Exception e) { - throw new ComponentException(ActionStatus.GENERAL_ERROR,e.getMessage()); + throw new ComponentException(ActionStatus.GENERAL_ERROR, e.getMessage()); } } protected void handleServiceNodeTypes(String yamlName, Service service, - String topologyTemplateYaml, boolean needLock, - Map>> nodeTypesArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, - CsarInfo csarInfo, String nodeName) { + String topologyTemplateYaml, boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, + CsarInfo csarInfo, String nodeName) { try { for (Map.Entry nodeTypeEntry : nodeTypesInfo.entrySet()) { boolean isResourceNotExisted = validateResourceNotExisted(nodeTypeEntry.getKey()); if (nodeTypeEntry.getValue().isNested() && isResourceNotExisted) { handleNestedVF(service, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, - nodeTypesInfo, csarInfo, nodeTypeEntry.getKey()); + nodeTypesInfo, csarInfo, nodeTypeEntry.getKey()); log.trace("************* finished to create node {}", nodeTypeEntry.getKey()); } } Map mappedToscaTemplate = null; if (org.apache.commons.lang.StringUtils.isNotEmpty(nodeName) && MapUtils.isNotEmpty(nodeTypesInfo) - && nodeTypesInfo.containsKey(nodeName)) { + && nodeTypesInfo.containsKey(nodeName)) { mappedToscaTemplate = nodeTypesInfo.get(nodeName).getMappedToscaTemplate(); } if (MapUtils.isEmpty(mappedToscaTemplate)) { mappedToscaTemplate = (Map) new Yaml().load(topologyTemplateYaml); } createResourcesFromYamlNodeTypesList(yamlName, service, mappedToscaTemplate, needLock, nodeTypesArtifactsToHandle, - nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); + nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo); } catch (ComponentException | StorageException e) { throw e; - } catch (Exception e){ - log.debug("Exception occured when handleServiceNodeTypes, error is:{}", e.getMessage(), e); + } catch (Exception e) { + log.debug("Exception occured when handleServiceNodeTypes, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } } @@ -2137,19 +2200,21 @@ public class ServiceImportBusinessLogic{ Either latestResource = toscaOperationFacade.getLatestResourceByToscaResourceName(type); return latestResource.isRight(); } catch (Exception e) { - log.debug("Exception occured when validateResourceNotExisted, error is:{}", e.getMessage(), e); + log.debug("Exception occured when validateResourceNotExisted, error is:{}", e.getMessage(), e); throw new ComponentException(ActionStatus.GENERAL_ERROR); } } - protected Resource handleNestedVF(Service service, Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - String nodeName) { + protected Resource handleNestedVF(Service service, + Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName) { try { String yamlName = nodesInfo.get(nodeName).getTemplateFileName(); Map nestedVfcJsonMap = nodesInfo.get(nodeName).getMappedToscaTemplate(); - createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo); + createResourcesFromYamlNodeTypesList(yamlName, service, nestedVfcJsonMap, false, nodesArtifactsToHandle, createdArtifacts, nodesInfo, + csarInfo); log.debug("************* Finished to create node types from yaml {}", yamlName); if (nestedVfcJsonMap.containsKey(TypeUtils.ToscaTagNamesEnum.TOPOLOGY_TEMPLATE.getElementName())) { @@ -2163,41 +2228,42 @@ public class ServiceImportBusinessLogic{ } } - protected Resource handleComplexVfc(Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - String nodeName, String yamlName) { + protected Resource handleComplexVfc( + Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName) { try { Resource oldComplexVfc = null; Resource newComplexVfc = serviceImportParseLogic.buildValidComplexVfc(csarInfo, nodeName, nodesInfo); Either oldComplexVfcRes = toscaOperationFacade - .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); + .getFullLatestComponentByToscaResourceName(newComplexVfc.getToscaResourceName()); if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() == StorageOperationStatus.NOT_FOUND) { oldComplexVfcRes = toscaOperationFacade.getFullLatestComponentByToscaResourceName( - serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), - nodeName).getRight()); + serviceImportParseLogic.buildNestedToscaResourceName(ResourceTypeEnum.VF.name(), csarInfo.getVfResourceName(), + nodeName).getRight()); } if (oldComplexVfcRes.isRight() && oldComplexVfcRes.right().value() != StorageOperationStatus.NOT_FOUND) { log.debug("Failed to fetch previous complex VFC by tosca resource name {}. Status is {}. ", - newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); + newComplexVfc.getToscaResourceName(), oldComplexVfcRes.right().value()); throw new ComponentException(ActionStatus.GENERAL_ERROR); } else if (oldComplexVfcRes.isLeft()) { log.debug(VALIDATE_DERIVED_BEFORE_UPDATE); Either eitherValidation = serviceImportParseLogic.validateNestedDerivedFromDuringUpdate( - oldComplexVfcRes.left().value(), newComplexVfc, - ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); + oldComplexVfcRes.left().value(), newComplexVfc, + ValidationUtils.hasBeenCertified(oldComplexVfcRes.left().value().getVersion())); if (eitherValidation.isLeft()) { oldComplexVfc = oldComplexVfcRes.left().value(); } } newComplexVfc = handleComplexVfc(nodesArtifactsToHandle, createdArtifacts, nodesInfo, csarInfo, nodeName, yamlName, - oldComplexVfc, newComplexVfc); + oldComplexVfc, newComplexVfc); csarInfo.getCreatedNodesToscaResourceNames().put(nodeName, newComplexVfc.getToscaResourceName()); LifecycleChangeInfoWithAction lifecycleChangeInfo = new LifecycleChangeInfoWithAction( - CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); + CERTIFICATION_ON_IMPORT, LifecycleChangeInfoWithAction.LifecycleChanceActionEnum.CREATE_FROM_CSAR); log.debug("Going to certify cvfc {}. ", newComplexVfc.getName()); final Resource result = serviceImportParseLogic - .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, - true); + .propagateStateToCertified(csarInfo.getModifier(), newComplexVfc, lifecycleChangeInfo, true, false, + true); csarInfo.getCreatedNodes().put(nodeName, result); csarInfo.removeNodeFromQueue(); return result; @@ -2207,23 +2273,24 @@ public class ServiceImportBusinessLogic{ } } - protected Resource handleComplexVfc(Map>> nodesArtifactsToHandle, - List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, - String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { + protected Resource handleComplexVfc( + Map>> nodesArtifactsToHandle, + List createdArtifacts, Map nodesInfo, CsarInfo csarInfo, + String nodeName, String yamlName, Resource oldComplexVfc, Resource newComplexVfc) { Resource handleComplexVfcRes; try { Map mappedToscaTemplate = nodesInfo.get(nodeName).getMappedToscaTemplate(); String yamlContent = new String(csarInfo.getCsar().get(yamlName)); Map newNodeTypesInfo = nodesInfo.entrySet().stream() - .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy())); + .collect(toMap(Map.Entry::getKey, e -> e.getValue().getUnmarkedCopy())); CsarInfo.markNestedVfc(mappedToscaTemplate, newNodeTypesInfo); if (oldComplexVfc == null) { handleComplexVfcRes = createResourceFromYaml(newComplexVfc, yamlContent, yamlName, newNodeTypesInfo, - csarInfo, nodesArtifactsToHandle, false, true, nodeName); + csarInfo, nodesArtifactsToHandle, false, true, nodeName); } else { handleComplexVfcRes = updateResourceFromYaml(oldComplexVfc, newComplexVfc, - AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo, - newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); + AuditingActionEnum.UPDATE_RESOURCE_METADATA, createdArtifacts, yamlContent, yamlName, csarInfo, + newNodeTypesInfo, nodesArtifactsToHandle, nodeName, true); } return handleComplexVfcRes; } catch (Exception e) { @@ -2233,44 +2300,49 @@ public class ServiceImportBusinessLogic{ } protected Resource updateResourceFromYaml(Resource oldRresource, Resource newRresource, - AuditingActionEnum actionEnum, List createdArtifacts, - String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map nodeTypesInfo, - Map>> nodeTypesArtifactsToHandle, - String nodeName, boolean isNested) { + AuditingActionEnum actionEnum, List createdArtifacts, + String yamlFileName, String yamlFileContent, CsarInfo csarInfo, Map nodeTypesInfo, + Map>> nodeTypesArtifactsToHandle, + String nodeName, boolean isNested) { boolean inTransaction = true; boolean shouldLock = false; Resource preparedResource = null; ParsedToscaYamlInfo uploadComponentInstanceInfoMap = null; try { - uploadComponentInstanceInfoMap = csarBusinessLogic.getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldRresource); + uploadComponentInstanceInfoMap = csarBusinessLogic + .getParsedToscaYamlInfo(yamlFileContent, yamlFileName, nodeTypesInfo, csarInfo, nodeName, oldRresource); Map instances = uploadComponentInstanceInfoMap.getInstances(); if (MapUtils.isEmpty(instances) && newRresource.getResourceType() != ResourceTypeEnum.PNF) { throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlFileName); } preparedResource = updateExistingResourceByImport(newRresource, oldRresource, csarInfo.getModifier(), - inTransaction, shouldLock, isNested).left; + inTransaction, shouldLock, isNested).left; log.trace("YAML topology file found in CSAR, file name: {}, contents: {}", yamlFileName, yamlFileContent); serviceImportParseLogic.handleResourceGenericType(preparedResource); handleNodeTypes(yamlFileName, preparedResource, yamlFileContent, - shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName); + shouldLock, nodeTypesArtifactsToHandle, createdArtifacts, nodeTypesInfo, csarInfo, nodeName); preparedResource = serviceImportParseLogic - .createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs()); + .createInputsOnResource(preparedResource, uploadComponentInstanceInfoMap.getInputs()); preparedResource = createResourceInstances(yamlFileName, preparedResource, instances, csarInfo.getCreatedNodes()); preparedResource = createResourceInstancesRelations(csarInfo.getModifier(), yamlFileName, preparedResource, instances); } catch (ComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); + ResponseFormat responseFormat = + e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum); + componentsUtils + .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum); throw e; } catch (StorageException e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); log.debug("#updateResourceFromYaml - failed to update resource from yaml {} .The error is {}", yamlFileName, responseFormat); - componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum); + componentsUtils + .auditResource(responseFormat, csarInfo.getModifier(), preparedResource == null ? oldRresource : preparedResource, actionEnum); throw e; } Either, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic - .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), - preparedResource.getSystemName()); + .validateUpdateVfGroupNames(uploadComponentInstanceInfoMap.getGroups(), + preparedResource.getSystemName()); if (validateUpdateVfGroupNamesRes.isRight()) { throw new ComponentException(validateUpdateVfGroupNamesRes.right().value()); } @@ -2283,11 +2355,11 @@ public class ServiceImportBusinessLogic{ serviceImportParseLogic.handleGroupsProperties(preparedResource, groups); preparedResource = serviceImportParseLogic.updateGroupsOnResource(preparedResource, groups); NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, - nodeTypesArtifactsToHandle); + nodeTypesArtifactsToHandle); Either updateArtifactsEither = createOrUpdateArtifacts( - ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName, - csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + ArtifactsBusinessLogic.ArtifactOperationEnum.UPDATE, createdArtifacts, yamlFileName, + csarInfo, preparedResource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); if (updateArtifactsEither.isRight()) { log.debug("failed to update artifacts {}", updateArtifactsEither.right().value()); throw new ComponentException(updateArtifactsEither.right().value()); @@ -2297,7 +2369,7 @@ public class ServiceImportBusinessLogic{ ActionStatus mergingPropsAndInputsStatus = resourceDataMergeBusinessLogic.mergeResourceEntities(oldRresource, preparedResource); if (mergingPropsAndInputsStatus != ActionStatus.OK) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource(mergingPropsAndInputsStatus, - preparedResource); + preparedResource); throw new ComponentException(responseFormat); } compositionBusinessLogic.setPositionsForComponentInstances(preparedResource, csarInfo.getModifier().getUserId()); @@ -2305,27 +2377,30 @@ public class ServiceImportBusinessLogic{ } protected Resource createResourceFromYaml(Resource resource, String topologyTemplateYaml, - String yamlName, Map nodeTypesInfo, CsarInfo csarInfo, - Map>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { + String yamlName, Map nodeTypesInfo, CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { List createdArtifacts = new ArrayList<>(); Resource createdResource; try { - ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic.getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource); + ParsedToscaYamlInfo parsedToscaYamlInfo = csarBusinessLogic + .getParsedToscaYamlInfo(topologyTemplateYaml, yamlName, nodeTypesInfo, csarInfo, nodeName, resource); if (MapUtils.isEmpty(parsedToscaYamlInfo.getInstances()) && resource.getResourceType() != ResourceTypeEnum.PNF) { throw new ComponentException(ActionStatus.NOT_TOPOLOGY_TOSCA_TEMPLATE, yamlName); } log.debug("#createResourceFromYaml - Going to create resource {} and RIs ", resource.getName()); createdResource = createResourceAndRIsFromYaml(yamlName, resource, - parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, - nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); + parsedToscaYamlInfo, AuditingActionEnum.IMPORT_RESOURCE, false, createdArtifacts, topologyTemplateYaml, + nodeTypesInfo, csarInfo, nodeTypesArtifactsToCreate, shouldLock, inTransaction, nodeName); log.debug("#createResourceFromYaml - The resource {} has been created ", resource.getName()); } catch (ComponentException e) { - ResponseFormat responseFormat = e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); + ResponseFormat responseFormat = + e.getResponseFormat() == null ? componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams()) : e.getResponseFormat(); componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); throw e; } catch (StorageException e) { - ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); + ResponseFormat responseFormat = componentsUtils + .getResponseFormat(componentsUtils.convertFromStorageResponse(e.getStorageOperationStatus())); componentsUtils.auditResource(responseFormat, csarInfo.getModifier(), resource, AuditingActionEnum.IMPORT_RESOURCE); throw e; } @@ -2333,15 +2408,15 @@ public class ServiceImportBusinessLogic{ } protected Resource createResourceAndRIsFromYaml(String yamlName, Resource resource, - ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, - List createdArtifacts, String topologyTemplateYaml, - Map nodeTypesInfo, CsarInfo csarInfo, - Map>> nodeTypesArtifactsToCreate, - boolean shouldLock, boolean inTransaction, String nodeName) { + ParsedToscaYamlInfo parsedToscaYamlInfo, AuditingActionEnum actionEnum, boolean isNormative, + List createdArtifacts, String topologyTemplateYaml, + Map nodeTypesInfo, CsarInfo csarInfo, + Map>> nodeTypesArtifactsToCreate, + boolean shouldLock, boolean inTransaction, String nodeName) { List nodeTypesNewCreatedArtifacts = new ArrayList<>(); if (shouldLock) { Either lockResult = serviceBusinessLogic.lockComponentByName(resource.getSystemName(), resource, - CREATE_RESOURCE); + CREATE_RESOURCE); if (lockResult.isRight()) { serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(lockResult.right().value()); @@ -2352,25 +2427,26 @@ public class ServiceImportBusinessLogic{ log.trace("************* createResourceFromYaml before full create resource {}", yamlName); Resource genericResource = serviceBusinessLogic.fetchAndSetDerivedFromGenericType(resource); resource = createResourceTransaction(resource, - csarInfo.getModifier(), isNormative); + csarInfo.getModifier(), isNormative); log.trace("************* Going to add inputs from yaml {}", yamlName); Map yamlMap = ImportUtils.loadYamlAsStrictMap(csarInfo.getMainTemplateContent()); Map metadata = (Map) yamlMap.get("metadata"); String type = (String) metadata.get("type"); - if (resource.shouldGenerateInputs() && !"Service".equalsIgnoreCase(type)) + if (resource.shouldGenerateInputs() && !"Service".equalsIgnoreCase(type)) { serviceBusinessLogic.generateAndAddInputsFromGenericTypeProperties(resource, genericResource); + } Map inputs = parsedToscaYamlInfo.getInputs(); resource = serviceImportParseLogic.createInputsOnResource(resource, inputs); Map uploadComponentInstanceInfoMap = parsedToscaYamlInfo - .getInstances(); + .getInstances(); resource = createRIAndRelationsFromYaml(yamlName, resource, uploadComponentInstanceInfoMap, - topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, - nodeTypesArtifactsToCreate, nodeName); + topologyTemplateYaml, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeTypesArtifactsToCreate, nodeName); log.trace("************* Finished to create nodes, RI and Relation from yaml {}", yamlName); // validate update vf module group names Either, ResponseFormat> validateUpdateVfGroupNamesRes = serviceBusinessLogic.groupBusinessLogic - .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName()); + .validateUpdateVfGroupNames(parsedToscaYamlInfo.getGroups(), resource.getSystemName()); if (validateUpdateVfGroupNamesRes.isRight()) { serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(validateUpdateVfGroupNamesRes.right().value()); @@ -2385,7 +2461,7 @@ public class ServiceImportBusinessLogic{ } Either createGroupsOnResource = createGroupsOnResource(resource, - groups); + groups); if (createGroupsOnResource.isRight()) { serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(createGroupsOnResource.right().value()); @@ -2396,8 +2472,8 @@ public class ServiceImportBusinessLogic{ NodeTypeInfoToUpdateArtifacts nodeTypeInfoToUpdateArtifacts = new NodeTypeInfoToUpdateArtifacts(nodeName, nodeTypesArtifactsToCreate); Either createArtifactsEither = createOrUpdateArtifacts( - ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, - csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); + ArtifactsBusinessLogic.ArtifactOperationEnum.CREATE, createdArtifacts, yamlName, + csarInfo, resource, nodeTypeInfoToUpdateArtifacts, inTransaction, shouldLock); if (createArtifactsEither.isRight()) { serviceImportParseLogic.rollback(inTransaction, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); throw new ComponentException(createArtifactsEither.right().value()); @@ -2416,20 +2492,21 @@ public class ServiceImportBusinessLogic{ serviceBusinessLogic.janusGraphDao.commit(); } if (shouldLock) { - serviceBusinessLogic.graphLockOperation.unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); + serviceBusinessLogic.graphLockOperation + .unlockComponentByName(resource.getSystemName(), resource.getUniqueId(), NodeTypeEnum.Resource); } } } protected Either createGroupsOnResource(Resource resource, - Map groups) { + Map groups) { if (groups != null && !groups.isEmpty()) { List groupsAsList = updateGroupsMembersUsingResource( - groups, resource); + groups, resource); serviceImportParseLogic.handleGroupsProperties(resource, groups); serviceImportParseLogic.fillGroupsFinalFields(groupsAsList); Either, ResponseFormat> createGroups = serviceBusinessLogic.groupBusinessLogic.createGroups(resource, - groupsAsList, true); + groupsAsList, true); if (createGroups.isRight()) { return Either.right(createGroups.right().value()); } @@ -2437,10 +2514,10 @@ public class ServiceImportBusinessLogic{ return Either.left(resource); } Either updatedResource = toscaOperationFacade - .getToscaElement(resource.getUniqueId()); + .getToscaElement(resource.getUniqueId()); if (updatedResource.isRight()) { ResponseFormat responseFormat = componentsUtils.getResponseFormatByResource( - componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); + componentsUtils.convertFromStorageResponse(updatedResource.right().value()), resource); return Either.right(responseFormat); } return Either.left(updatedResource.left().value()); @@ -2470,22 +2547,23 @@ public class ServiceImportBusinessLogic{ return result; } - protected void updateGroupMembers(Map groups, GroupDefinition updatedGroupDefinition, Resource component, List componentInstances, String groupName, Map members) { + protected void updateGroupMembers(Map groups, GroupDefinition updatedGroupDefinition, Resource component, + List componentInstances, String groupName, Map members) { Set compInstancesNames = members.keySet(); if (CollectionUtils.isEmpty(componentInstances)) { String membersAstString = compInstancesNames.stream().collect(joining(",")); log.debug("The members: {}, in group: {}, cannot be found in component {}. There are no component instances.", - membersAstString, groupName, component.getNormalizedName()); + membersAstString, groupName, component.getNormalizedName()); throw new ComponentException(componentsUtils.getResponseFormat( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, - component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component))); + ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, + component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component))); } Map memberNames = componentInstances.stream() - .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); + .collect(toMap(ComponentInstance::getName, ComponentInstance::getUniqueId)); memberNames.putAll(groups.keySet().stream().collect(toMap(g -> g, g -> ""))); Map relevantInstances = memberNames.entrySet().stream() - .filter(n -> compInstancesNames.contains(n.getKey())) - .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); + .filter(n -> compInstancesNames.contains(n.getKey())) + .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); if (relevantInstances == null || relevantInstances.size() != compInstancesNames.size()) { List foundMembers = new ArrayList<>(); @@ -2495,25 +2573,25 @@ public class ServiceImportBusinessLogic{ compInstancesNames.removeAll(foundMembers); String membersAstString = compInstancesNames.stream().collect(joining(",")); throw new ComponentException(componentsUtils.getResponseFormat( - ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, - component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component))); + ActionStatus.GROUP_INVALID_COMPONENT_INSTANCE, membersAstString, groupName, + component.getNormalizedName(), serviceImportParseLogic.getComponentTypeForResponse(component))); } updatedGroupDefinition.setMembers(relevantInstances); } protected Resource createResourceTransaction(Resource resource, User user, - boolean isNormative) { + boolean isNormative) { Either eitherValidation = toscaOperationFacade.validateComponentNameExists( - resource.getName(), resource.getResourceType(), resource.getComponentType()); + resource.getName(), resource.getResourceType(), resource.getComponentType()); if (eitherValidation.isRight()) { ResponseFormat errorResponse = componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); + .getResponseFormat(componentsUtils.convertFromStorageResponse(eitherValidation.right().value())); throw new ComponentException(errorResponse); } if (eitherValidation.left().value()) { log.debug("resource with name: {}, already exists", resource.getName()); ResponseFormat errorResponse = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, - ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); + ComponentTypeEnum.RESOURCE.getValue(), resource.getName()); throw new ComponentException(errorResponse); } log.debug("send resource {} to dao for create", resource.getName()); @@ -2528,36 +2606,37 @@ public class ServiceImportBusinessLogic{ } } return toscaOperationFacade.createToscaComponent(resource) - .left() - .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource)); + .left() + .on(r -> serviceImportParseLogic.throwComponentExceptionByResource(r, resource)); } protected ImmutablePair updateExistingResourceByImport( - Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, - boolean isNested) { + Resource newResource, Resource oldResource, User user, boolean inTransaction, boolean needLock, + boolean isNested) { String lockedResourceId = oldResource.getUniqueId(); log.debug("found resource: name={}, id={}, version={}, state={}", oldResource.getName(), lockedResourceId, - oldResource.getVersion(), oldResource.getLifecycleState()); + oldResource.getVersion(), oldResource.getLifecycleState()); ImmutablePair resourcePair = null; try { serviceBusinessLogic.lockComponent(lockedResourceId, oldResource, needLock, "Update Resource by Import"); oldResource = serviceImportParseLogic - .prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false); + .prepareResourceForUpdate(oldResource, newResource, user, inTransaction, false); serviceImportParseLogic.mergeOldResourceMetadataWithNew(oldResource, newResource); serviceImportParseLogic.validateResourceFieldsBeforeUpdate(oldResource, newResource, inTransaction, isNested); serviceImportParseLogic - .validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource, AuditingActionEnum.IMPORT_RESOURCE, inTransaction); + .validateCapabilityTypesCreate(user, serviceImportParseLogic.getCapabilityTypeOperation(), newResource, + AuditingActionEnum.IMPORT_RESOURCE, inTransaction); createNewResourceToOldResource(newResource, oldResource, user); Either overrideResource = toscaOperationFacade - .overrideComponent(newResource, oldResource); + .overrideComponent(newResource, oldResource); if (overrideResource.isRight()) { ResponseFormat responseFormat = new ResponseFormat(); serviceBusinessLogic.throwComponentException(responseFormat); } log.debug("Resource updated successfully!!!"); resourcePair = new ImmutablePair<>(overrideResource.left().value(), - ActionStatus.OK); + ActionStatus.OK); return resourcePair; } finally { if (resourcePair == null) { @@ -2609,52 +2688,58 @@ public class ServiceImportBusinessLogic{ } } - protected Map createResourcesFromYamlNodeTypesList(String yamlName, Service service, Map mappedToscaTemplate, boolean needLock, - Map>> nodeTypesArtifactsToHandle, - List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, - CsarInfo csarInfo) { + protected Map createResourcesFromYamlNodeTypesList(String yamlName, Service service, Map mappedToscaTemplate, + boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, + Map nodeTypesInfo, + CsarInfo csarInfo) { try { Either toscaVersion = findFirstToscaStringElement(mappedToscaTemplate, - TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); + TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION); if (toscaVersion.isRight()) { throw new ComponentException(ActionStatus.INVALID_TOSCA_TEMPLATE); } Map mapToConvert = new HashMap<>(); mapToConvert.put(TypeUtils.ToscaTagNamesEnum.TOSCA_VERSION.getElementName(), toscaVersion.left().value()); Map nodeTypes = serviceImportParseLogic.getNodeTypesFromTemplate(mappedToscaTemplate); - createNodeTypes(yamlName, service, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, mapToConvert, nodeTypes); + createNodeTypes(yamlName, service, needLock, nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + mapToConvert, nodeTypes); return csarInfo.getCreatedNodes(); } catch (Exception e) { - log.debug("Exception occured when createResourcesFromYamlNodeTypesList,error is:{}",e.getMessage(),e); - throw new ComponentException(ActionStatus.GENERAL_ERROR); + log.debug("Exception occured when createResourcesFromYamlNodeTypesList,error is:{}", e.getMessage(), e); + throw new ComponentException(ActionStatus.GENERAL_ERROR); } } - protected void createNodeTypes(String yamlName, Service service, boolean needLock, Map>> nodeTypesArtifactsToHandle, List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, CsarInfo csarInfo, Map mapToConvert, Map nodeTypes) { + protected void createNodeTypes(String yamlName, Service service, boolean needLock, + Map>> nodeTypesArtifactsToHandle, + List nodeTypesNewCreatedArtifacts, Map nodeTypesInfo, CsarInfo csarInfo, + Map mapToConvert, Map nodeTypes) { Iterator> nodesNameValueIter = nodeTypes.entrySet().iterator(); Resource vfcCreated = null; while (nodesNameValueIter.hasNext()) { Map.Entry nodeType = nodesNameValueIter.next(); Map> nodeTypeArtifactsToHandle = nodeTypesArtifactsToHandle == null - || nodeTypesArtifactsToHandle.isEmpty() ? null - : nodeTypesArtifactsToHandle.get(nodeType.getKey()); + || nodeTypesArtifactsToHandle.isEmpty() ? null + : nodeTypesArtifactsToHandle.get(nodeType.getKey()); if (nodeTypesInfo.containsKey(nodeType.getKey())) { vfcCreated = handleNestedVfc(service, - nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, - nodeType.getKey()); + nodeTypesArtifactsToHandle, nodeTypesNewCreatedArtifacts, nodeTypesInfo, csarInfo, + nodeType.getKey()); log.trace("************* Finished to handle nested vfc {}", nodeType.getKey()); } else if (csarInfo.getCreatedNodesToscaResourceNames() != null - && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) { + && !csarInfo.getCreatedNodesToscaResourceNames().containsKey(nodeType.getKey())) { ImmutablePair resourceCreated = serviceImportParseLogic - .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, - service, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, - csarInfo, true); + .createNodeTypeResourceFromYaml(yamlName, nodeType, csarInfo.getModifier(), mapToConvert, + service, needLock, nodeTypeArtifactsToHandle, nodeTypesNewCreatedArtifacts, true, + csarInfo, true); log.debug("************* Finished to create node {}", nodeType.getKey()); vfcCreated = resourceCreated.getLeft(); csarInfo.getCreatedNodesToscaResourceNames().put(nodeType.getKey(), - vfcCreated.getName()); + vfcCreated.getName()); } if (vfcCreated != null) { csarInfo.getCreatedNodes().put(nodeType.getKey(), vfcCreated); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java index cf70d39743..a86d6047d4 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogic.java @@ -2260,7 +2260,7 @@ public class ServiceImportParseLogic { } } - public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map> instAttributes) { + public void associateInstAttributeToComponentToInstances(String yamlName, Resource resource, Map> instAttributes) { StorageOperationStatus addArtToInst; addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, @@ -2375,7 +2375,7 @@ public class ServiceImportParseLogic { } } - public void associateInstAttributeToComponentToInstances(String yamlName, Service resource, Map> instAttributes) { + public void associateInstAttributeToComponentToInstances(String yamlName, Service resource, Map> instAttributes) { StorageOperationStatus addArtToInst; addArtToInst = toscaOperationFacade.associateInstAttributeToComponentToInstances(instAttributes, diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java index ee01aa0801..888ad2b71c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/merge/instance/ComponentInstanceMergeDataBusinessLogic.java @@ -102,7 +102,7 @@ public class ComponentInstanceMergeDataBusinessLogic { filter.setIgnoreCapabilities(false); filter.setIgnoreCapabiltyProperties(false); filter.setIgnoreArtifacts(false); - filter.setIgnoreForwardingPath(false); + filter.setIgnoreServicePath(false); filter.setIgnoreComponentInstancesInterfaces(false); return toscaOperationFacade.getToscaElement(containerComponentId, filter); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java index 9d1167a8c1..9150e5e91e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/path/ForwardingPathValidator.java @@ -114,7 +114,7 @@ public class ForwardingPathValidator { boolean isUpdate, ResponseFormatManager responseFormatManager) { boolean isPathNameUnique = false; ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreForwardingPath(false); + filter.setIgnoreServicePath(false); Either forwardingPathOrigin = toscaOperationFacade .getToscaElement(serviceId, filter); if (forwardingPathOrigin.isRight()){ diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java index 494ec9c6e8..6e23454a62 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/UiComponentDataConverter.java @@ -138,6 +138,9 @@ public class UiComponentDataConverter { case PROPERTIES: setProperties(dataTransfer, component); break; + case ATTRIBUTES: + setAttributes(dataTransfer, component); + break; case INTERFACES: setInterfaces(dataTransfer, component); break; @@ -308,6 +311,14 @@ public class UiComponentDataConverter { } } + private void setAttributes(final UiComponentDataTransfer dataTransfer, final Component component) { + if (component.getAttributes() == null) { + dataTransfer.setAttributes(new ArrayList<>()); + } else { + dataTransfer.setAttributes(component.getAttributes()); + } + } + private void setInterfaces(UiComponentDataTransfer dataTransfer, Component component) { if (component.getInterfaces() == null) { dataTransfer.setInterfaces(new HashMap<>()); @@ -385,7 +396,7 @@ public class UiComponentDataConverter { final SubstitutionFilterConverter substitutionFilterConverter = new SubstitutionFilterConverter(); final Map filterUiMap = new HashMap<>(); filterUiMap.put(resource.getUniqueId(), - substitutionFilterConverter.convertToUi(resource.getSubstitutionFilter())); + substitutionFilterConverter.convertToUi(resource.getSubstitutionFilter())); dataTransfer.setSubstitutionFilterForTopologyTemplate(filterUiMap); } break; 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 b4b2c15dcb..a1500a4204 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -58,6 +58,7 @@ 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.AttributeDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.user.UserBusinessLogic; import org.openecomp.sdc.common.api.Constants; @@ -69,9 +70,8 @@ import org.springframework.stereotype.Controller; /** * Web Servlet for actions on Attributes - * - * @author mshitrit * + * @author mshitrit */ @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Path("/v1/catalog") @@ -79,13 +79,15 @@ import org.springframework.stereotype.Controller; @Server(url = "/sdc2/rest") @Controller public class AttributeServlet extends AbstractValidationsServlet { + private static final Logger log = Logger.getLogger(AttributeServlet.class); private static final String ATTRIBUTE_CONTENT_IS_INVALID = "Attribute content is invalid - {}"; + @Inject public AttributeServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager) { + ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, + ResourceImportManager resourceImportManager) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); } @@ -103,18 +105,19 @@ public class AttributeServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Create Resource Attribute", method = "POST", - summary = "Returns created resource attribute", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Resource property created"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "409", description = "Resource attribute already exist")}) + summary = "Returns created resource attribute", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Resource property created"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "409", description = "Resource attribute already exist")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response createAttribute( - @Parameter(description = "resource id to update with new attribute", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "Resource attribute to be created", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { + @Parameter(description = "resource id to update with new attribute", + required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "Resource attribute to be created", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { ServletContext context = request.getSession().getServletContext(); @@ -123,12 +126,11 @@ public class AttributeServlet extends AbstractValidationsServlet { try { final Wrapper errorWrapper = new Wrapper<>(); - AttributeDataDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper); + AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper); if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either createAttribute = businessLogic - .createAttribute(resourceId, attributeDataDefinition, userId); + Either createAttribute = businessLogic.createAttribute(resourceId, attributeDataDefinition, userId); if (createAttribute.isRight()) { errorWrapper.setInnerElement(createAttribute.right().value()); } else { @@ -136,18 +138,15 @@ public class AttributeServlet extends AbstractValidationsServlet { } } - Response response; if (!errorWrapper.isEmpty()) { log.info("Failed to create Attribute. Reason - ", errorWrapper.getInnerElement()); - response = buildErrorResponse(errorWrapper.getInnerElement()); + return buildErrorResponse(errorWrapper.getInnerElement()); } else { log.debug("Attribute {} created successfully with id {}", attributeDataDefinition.getName(), attributeDataDefinition.getUniqueId()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.CREATED); - response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition)); + return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition)); } - return response; - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create Attribute"); log.debug("create property failed with exception", e); @@ -170,19 +169,20 @@ public class AttributeServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Update Resource Attribute", method = "PUT", summary = "Returns updated attribute", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "200", description = "Resource attribute updated"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + responses = {@ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Resource attribute updated"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response updateAttribute( - @Parameter(description = "resource id to update with new attribute", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "attribute id to update", - required = true) @PathParam("attributeId") final String attributeId, - @Parameter(description = "Resource attribute to update", required = true) String data, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { + @Parameter(description = "resource id to update with new attribute", + required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "attribute id to update", + required = true) @PathParam("attributeId") final String attributeId, + @Parameter(description = "Resource attribute to update", required = true) String data, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { ServletContext context = request.getSession().getServletContext(); @@ -196,11 +196,11 @@ public class AttributeServlet extends AbstractValidationsServlet { try { final Wrapper errorWrapper = new Wrapper<>(); - AttributeDataDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper); + AttributeDefinition attributeDataDefinition = convertJsonToObject(data, errorWrapper); if (errorWrapper.isEmpty()) { AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherUpdateAttribute = businessLogic - .updateAttribute(resourceId, attributeId, attributeDataDefinition, userId); + Either eitherUpdateAttribute + = businessLogic.updateAttribute(resourceId, attributeId, attributeDataDefinition, userId); if (eitherUpdateAttribute.isRight()) { errorWrapper.setInnerElement(eitherUpdateAttribute.right().value()); } else { @@ -208,18 +208,15 @@ public class AttributeServlet extends AbstractValidationsServlet { } } - Response response; if (!errorWrapper.isEmpty()) { log.info("Failed to update Attribute. Reason - ", errorWrapper.getInnerElement()); - response = buildErrorResponse(errorWrapper.getInnerElement()); + return buildErrorResponse(errorWrapper.getInnerElement()); } else { log.debug("Attribute id {} updated successfully ", attributeDataDefinition.getUniqueId()); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.OK); - response = buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition)); + return buildOkResponse(responseFormat, RepresentationUtils.toRepresentation(attributeDataDefinition)); } - return response; - } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Update Attribute"); log.debug("update attribute failed with exception", e); @@ -241,19 +238,20 @@ public class AttributeServlet extends AbstractValidationsServlet { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Operation(description = "Create Resource Attribute", method = "DELETE", summary = "Returns deleted attribute", - responses = {@ApiResponse( - content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "204", description = "deleted attribute"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), - @ApiResponse(responseCode = "404", description = "Resource property not found")}) + responses = {@ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "204", description = "deleted attribute"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Resource property not found")}) @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) public Response deleteAttribute( - @Parameter(description = "resource id of attribute", - required = true) @PathParam("resourceId") final String resourceId, - @Parameter(description = "Attribute id to delete", - required = true) @PathParam("attributeId") final String attributeId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) throws IOException { + @Parameter(description = "resource id of attribute", + required = true) @PathParam("resourceId") final String resourceId, + @Parameter(description = "Attribute id to delete", + required = true) @PathParam("attributeId") final String attributeId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) + throws IOException { ServletContext context = request.getSession().getServletContext(); @@ -263,13 +261,15 @@ public class AttributeServlet extends AbstractValidationsServlet { try { // delete the property - AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, () -> AttributeBusinessLogic.class); - Either eitherAttribute = businessLogic.deleteAttribute(resourceId, attributeId, userId); + AttributeBusinessLogic businessLogic = getClassFromWebAppContext(context, + () -> AttributeBusinessLogic.class); + 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()); } - AttributeDataDefinition attributeDefinition = eitherAttribute.left().value(); + AttributeDefinition attributeDefinition = eitherAttribute.left().value(); String name = attributeDefinition.getName(); log.debug("Attribute {} deleted successfully with id {}", name, attributeDefinition.getUniqueId()); @@ -284,7 +284,7 @@ public class AttributeServlet extends AbstractValidationsServlet { } private void buildAttributeFromString(String data, Wrapper attributesWrapper, - Wrapper errorWrapper) { + Wrapper errorWrapper) { try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); final AttributeDataDefinition attribute = gson.fromJson(data, AttributeDataDefinition.class); @@ -304,12 +304,12 @@ public class AttributeServlet extends AbstractValidationsServlet { } } - private AttributeDataDefinition convertJsonToObject(final String data, - final Wrapper errorWrapper) { + private AttributeDefinition convertJsonToObject(final String data, + final Wrapper errorWrapper) { final ObjectMapper mapper = new ObjectMapper(); try { - return mapper.readValue(data, AttributeDataDefinition.class); + return mapper.readValue(data, AttributeDefinition.class); } catch (final IOException e) { log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, ATTRIBUTE_CONTENT_IS_INVALID, data); ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentAttributeServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentAttributeServlet.java new file mode 100644 index 0000000000..19df0e2cc6 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentAttributeServlet.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2021, Nordix Foundation. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +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.tags.Tag; +import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.openecomp.sdc.be.components.impl.AttributeBusinessLogic; +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.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.AttributeDefinition; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Path("/v1/catalog") +@Tag(name = "SDC Internal APIs") +@Server(url = "/sdc2/rest") +@Singleton +public class ComponentAttributeServlet extends BeGenericServlet { + + private final AttributeBusinessLogic attributeBusinessLogic; + + @Inject + public ComponentAttributeServlet(final UserBusinessLogic userBusinessLogic, + final ComponentsUtils componentsUtils, + final AttributeBusinessLogic attributeBusinessLogic) { + super(userBusinessLogic, componentsUtils); + this.attributeBusinessLogic = attributeBusinessLogic; + } + + private static final Logger log = LoggerFactory.getLogger(ComponentAttributeServlet.class); + private static final String CREATE_ATTRIBUTE = "Create Attribute"; + private static final String DEBUG_MESSAGE = "Start handle request of {} modifier id is {}"; + + @GET + @Path("services/{serviceId}/attributes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Operation(description = "Get Service Attribute", method = "GET", summary = "Returns attribute list of service", + responses = {@ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "attribute"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Service attribute not found")}) + @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) + public Response getAttributeListInService( + @Parameter(description = "service id of attribute", + required = true) @PathParam("serviceId") final String serviceId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) { + + return getAttributeList(serviceId, request, userId); + } + + @GET + @Path("resources/{resourceId}/attributes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Operation(description = "Get Resource Attribute", method = "GET", summary = "Returns attribute list of resource", + responses = {@ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "attribute"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content"), + @ApiResponse(responseCode = "404", description = "Resource attribute not found")}) + @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) + public Response getAttributeListInResource( + @Parameter(description = "resource id of attribute", + required = true) @PathParam("resourceId") final String resourceId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) { + + return getAttributeList(resourceId, request, userId); + } + + private Response getAttributeList(final String componentId, final HttpServletRequest request, final String userId) { + + final String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(DEBUG_MESSAGE, url, userId); + + try { + final Either, ResponseFormat> attributesList = + attributeBusinessLogic.getAttributesList(componentId, userId); + + if (attributesList.isRight()) { + return buildErrorResponse(attributesList.right().value()); + } + + return buildOkResponse(attributesList.left().value()); + + } catch (final Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(CREATE_ATTRIBUTE); + log.debug("get attribute failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java index c5c89f7665..245ebc1bb8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java @@ -86,6 +86,7 @@ import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; import org.openecomp.sdc.be.info.GroupDefinitionInfo; 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.ComponentInstanceProperty; import org.openecomp.sdc.be.model.PropertyConstraint; @@ -1004,6 +1005,30 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstancePropertiesById); } + @GET + @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/attributes") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Operation(description = "Get component instance attributes", method = "GET", + summary = "Returns component instance attributes", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "200", description = "Attributes found"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component/Component Instance - not found")}) + @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) + public Response getInstanceAttributesById(@PathParam("containerComponentType") final String containerComponentType, + @PathParam("containerComponentId") final String containerComponentId, + @PathParam("componentInstanceUniqueId") final String componentInstanceUniqueId, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) { + + final String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(GET_START_HANDLE_REQUEST_OF, url); + + final List componentInstanceAttributesById = componentInstanceBusinessLogic + .getComponentInstanceAttributesById(containerComponentType, containerComponentId, componentInstanceUniqueId, userId); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), componentInstanceAttributesById); + } + // US330353 @GET @Path("/{containerComponentType}/{containerComponentId}/componentInstances/{componentInstanceUniqueId}/capability/{capabilityType}/capabilityName/{capabilityName}/ownerId/{ownerId}/properties") @@ -1385,6 +1410,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return convertStatus.left().value(); } + @Override public Either convertJsonToObject(String data, Class clazz) { try { log.trace("convert json to object. json=\n {}", data); @@ -1673,7 +1699,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { ReplaceVNFInfo replaceVNFInfo = convertResponse.left().value(); String serviceUniqueId = replaceVNFInfo.getServiceUniqueId(); String abstractResourceUniqueId = replaceVNFInfo.getAbstractResourceUniqueId(); - + ComponentInstance componentInstance = replaceVNFInfo.getRealVNFComponentInstance(); log.debug("replaceVNF:get ReplaceVNFInfo,serviceUniqueId:{},abstractResourceUniqueId:{}", serviceUniqueId,abstractResourceUniqueId); @@ -1681,7 +1707,6 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { /** * delete vnf */ - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); if (componentInstanceBusinessLogic == null) { log.debug("replaceVNF:Unsupported component type {}", containerComponentType); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/OutputsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/OutputsServlet.java new file mode 100644 index 0000000000..16e6d79879 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/OutputsServlet.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2021, Nordix Foundation. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import com.jcabi.aspects.Loggable; +import fj.data.Either; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.ArraySchema; +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.tags.Tag; +import java.io.IOException; +import java.util.List; +import javax.inject.Inject; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.OutputsBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.model.ComponentInstanceOutput; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.stereotype.Controller; + +@Loggable(prepend = true, value = Loggable.DEBUG, trim = false) +@Tag(name = "SDC Internal APIs") +@Server(url = "/sdc2/rest") +@Path("/v1/catalog") +@Controller +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class OutputsServlet extends AbstractValidationsServlet { + + private static final Logger log = Logger.getLogger(OutputsServlet.class); + private static final String START_HANDLE_REQUEST_OF = "(get) Start handle request of {}"; + + private final OutputsBusinessLogic outputsBusinessLogic; + + @Inject + public OutputsServlet(final UserBusinessLogic userBusinessLogic, + final OutputsBusinessLogic outputsBusinessLogic, + final ComponentInstanceBusinessLogic componentInstanceBL, + final ComponentsUtils componentsUtils, + final ServletUtils servletUtils, + final ResourceImportManager resourceImportManager) { + super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); + this.outputsBusinessLogic = outputsBusinessLogic; + } + + @GET + @Path("/{componentType}/{componentId}/componentInstances/{instanceId}/{originComponentUid}/outputs") + @Operation(description = "Get Outputs only", method = "GET", summary = "Returns Outputs list", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Resource.class)))), + @ApiResponse(responseCode = "200", description = "Component found"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "404", description = "Component not found")}) + public Response getComponentInstanceOutputs(@PathParam("componentType") final String componentType, + @PathParam("componentId") final String componentId, + @PathParam("instanceId") final String instanceId, + @PathParam("originComponentUid") final String originComponentUid, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) final String userId) throws IOException { + + final String url = request.getMethod() + " " + request.getRequestURI(); + log.debug(START_HANDLE_REQUEST_OF, url); + + try { + final Either, ResponseFormat> outputsResponse = + outputsBusinessLogic.getComponentInstanceOutputs(userId, componentId, instanceId); + if (outputsResponse.isRight()) { + log.debug("failed to get component instance outputs {}", componentType); + return buildErrorResponse(outputsResponse.right().value()); + } + final Object outputs = RepresentationUtils.toRepresentation(outputsResponse.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), outputs); + + } catch (final Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Outputs " + componentType); + log.debug("getOutputs failed with exception", e); + throw e; + } + } + +} 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 b4bf4e8d42..70834fd39a 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,7 +54,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.commons.lang3.tuple.Triple; -import org.onap.sdc.tosca.datatypes.model.AttributeDefinition; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.be.components.impl.exceptions.SdcResourceNotFoundException; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -76,6 +75,7 @@ import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.exception.ToscaExportException; 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.Component; @@ -403,10 +403,10 @@ public class ToscaExportHandler { private void convertSubstitutionMappingFilter(final Component component, final SubstitutionMapping substitutionMapping) { - if(component.getSubstitutionFilter() != null - && (component.getSubstitutionFilter().getProperties()).getListToscaDataDefinition() != null) { + if (component.getSubstitutionFilter() != null + && (component.getSubstitutionFilter().getProperties()).getListToscaDataDefinition() != null) { substitutionMapping - .setSubstitution_filter(convertToSubstitutionFilterComponent(component.getSubstitutionFilter())); + .setSubstitution_filter(convertToSubstitutionFilterComponent(component.getSubstitutionFilter())); } } @@ -584,7 +584,8 @@ public class ToscaExportHandler { final ComponentInstance componentInstance, final Component fetchedComponent) { componentCache.put(fetchedComponent.getUniqueId(), fetchedComponent); - if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) { + if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy + || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) { final Either sourceService = toscaOperationFacade .getToscaFullElement(componentInstance.getSourceModelUid()); if (sourceService.isRight() && (log.isDebugEnabled())) { @@ -1071,7 +1072,7 @@ public class ToscaExportHandler { toscaNodeType.setDerived_from(derivedFrom); } if (component instanceof Resource) { - final List attributes = ((Resource) component).getAttributes(); + final List attributes = ((Resource) component).getAttributes(); if (CollectionUtils.isNotEmpty(attributes)) { final Map attributeDataDefinitionMap = new HashMap<>(); attributes.forEach(attributeDataDefinition -> @@ -1083,16 +1084,16 @@ public class ToscaExportHandler { return toscaNodeType; } - private void buildAttributeData(final AttributeDataDefinition originalAttributeDataDefinition, + private void buildAttributeData(final AttributeDefinition originalAttributeDefinition, final Map attributeDataDefinitionMap) { - attributeDataDefinitionMap.put(originalAttributeDataDefinition.getName(), - new ObjectMapper().convertValue(new AttributeDefinition( - originalAttributeDataDefinition.getType(), - originalAttributeDataDefinition.getDescription(), - originalAttributeDataDefinition.get_default(), - originalAttributeDataDefinition.getStatus(), - originalAttributeDataDefinition.getEntry_schema()), Object.class)); + attributeDataDefinitionMap.put(originalAttributeDefinition.getName(), + new ObjectMapper().convertValue(new org.onap.sdc.tosca.datatypes.model.AttributeDefinition( + originalAttributeDefinition.getType(), + originalAttributeDefinition.getDescription(), + originalAttributeDefinition.get_default(), + originalAttributeDefinition.getStatus(), + originalAttributeDefinition.getEntry_schema()), Object.class)); } private Either, ToscaError> createProxyInterfaceTypes(Component container) { @@ -1206,19 +1207,21 @@ public class ToscaExportHandler { } private void createServiceSubstitutionNodeTypes(final Map componentCache, - final Component container, final ToscaTemplate toscaNode) { + final Component container, final ToscaTemplate toscaNode) { final List componentInstances = container.getComponentInstances(); if (CollectionUtils.isEmpty(componentInstances)) { return; } final List serviceSubstitutionInstanceList = componentInstances.stream() - .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceSubstitution.name())) - .collect(Collectors.toList()); + .filter(p -> p.getOriginType().name().equals(OriginTypeEnum.ServiceSubstitution.name())) + .collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(serviceSubstitutionInstanceList)) { for (ComponentInstance inst : serviceSubstitutionInstanceList) { - final Map nodeTypes = toscaNode.getNode_types() == null ? new HashMap<>() : toscaNode.getNode_types(); - convertInterfaceNodeType(new HashMap<>(), componentCache.get(inst.getSourceModelUid()), toscaNode, nodeTypes, true); + final Map nodeTypes = + toscaNode.getNode_types() == null ? new HashMap<>() : toscaNode.getNode_types(); + convertInterfaceNodeType(new HashMap<>(), componentCache.get(inst.getSourceModelUid()), toscaNode, + nodeTypes, true); } } } @@ -1576,7 +1579,7 @@ public class ToscaExportHandler { NodeFilter nodeFilter = new NodeFilter(); ListDataDefinition origProperties = - substitutionFilterDataDefinition.getProperties(); + substitutionFilterDataDefinition.getProperties(); List>> propertiesCopy = new ArrayList<>(); copySubstitutionFilterProperties(origProperties, propertiesCopy); @@ -1658,7 +1661,8 @@ public class ToscaExportHandler { for (final RequirementSubstitutionFilterPropertyDataDefinition propertyDataDefinition : origProperties .getListToscaDataDefinition()) { for (final String propertyInfoEntry : propertyDataDefinition.getConstraints()) { - final Map> propertyValObj = new YamlUtil().yamlToObject(propertyInfoEntry, Map.class); + final Map> propertyValObj = new YamlUtil() + .yamlToObject(propertyInfoEntry, Map.class); final String propertyName = propertyDataDefinition.getName(); if (propertyMapCopy.containsKey(propertyName)) { addPropertyConstraintValueToList(propertyName, propertyValObj, propertyMapCopy.get(propertyName)); @@ -1887,7 +1891,7 @@ public class ToscaExportHandler { return Collections.emptyMap(); } return component.getOutputs().stream() - .map(PropertyDataDefinition::getName) + .map(AttributeDataDefinition::getName) .collect( Collectors.toMap( outputName -> outputName, 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 0b11b2e0cf..7b0b40cc8b 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 @@ -39,7 +39,6 @@ import org.mockito.Mockito; import org.openecomp.sdc.be.components.validation.UserValidations; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.Component; @@ -56,323 +55,325 @@ import org.openecomp.sdc.exception.ResponseFormat; public class AttributeBusinessLogicTest extends BaseBusinessLogicMock { - private AttributeBusinessLogic createTestSubject() { - return new AttributeBusinessLogic(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, - interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation ); - } - - private UserValidations userValidations = Mockito.mock(UserValidations.class); - private ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); - private JanusGraphDao janusGraphDao = Mockito.mock(JanusGraphDao.class); - private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - private ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); - private AttributeOperation attributeOperation = Mockito.mock(AttributeOperation.class); - private Field baseBusinessLogic; - private AttributeBusinessLogic attributeBusinessLogic=createTestSubject(); - private IGraphLockOperation igraphLockOperation = Mockito.mock(IGraphLockOperation.class); - - @Before - public void setup() throws Exception { - baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("graphLockOperation"); - baseBusinessLogic.setAccessible(true); - baseBusinessLogic.set(attributeBusinessLogic, igraphLockOperation); - - final Field baseBusinessLogic1 = attributeBusinessLogic.getClass().getSuperclass() - .getDeclaredField("userValidations"); - baseBusinessLogic1.setAccessible(true); - baseBusinessLogic1.set(attributeBusinessLogic, userValidations); - - final Field baseBusinessLogic2 = attributeBusinessLogic.getClass().getSuperclass() - .getDeclaredField("componentsUtils"); - baseBusinessLogic2.setAccessible(true); - baseBusinessLogic2.set(attributeBusinessLogic, componentsUtils); - - final Field baseBusinessLogic3 = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("janusGraphDao"); - baseBusinessLogic3.setAccessible(true); - baseBusinessLogic3.set(attributeBusinessLogic, janusGraphDao); - - baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("toscaOperationFacade"); - baseBusinessLogic.setAccessible(true); - baseBusinessLogic.set(attributeBusinessLogic, toscaOperationFacade); - - baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("applicationDataTypeCache"); - baseBusinessLogic.setAccessible(true); - baseBusinessLogic.set(attributeBusinessLogic, applicationDataTypeCache); - - baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("attributeOperation"); - baseBusinessLogic.setAccessible(true); - baseBusinessLogic.set(attributeBusinessLogic, attributeOperation); - } - - @Test - public void createAttribute_lockfail() { - Either response; - response = attributeBusinessLogic.createAttribute("RES01", new AttributeDataDefinition(), "USR01"); - assertTrue(response.isRight()); - } - - @Test - public void createAttribute_Success() { - Component resource = new Resource(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setIsDeleted(false); - resource.setLastUpdaterUserId("USR01"); + private AttributeBusinessLogic createTestSubject() { + return new AttributeBusinessLogic(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, + interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); + } + + private UserValidations userValidations = Mockito.mock(UserValidations.class); + private ComponentsUtils componentsUtils = Mockito.mock(ComponentsUtils.class); + private JanusGraphDao janusGraphDao = Mockito.mock(JanusGraphDao.class); + private ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); + private ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); + private AttributeOperation attributeOperation = Mockito.mock(AttributeOperation.class); + private Field baseBusinessLogic; + private AttributeBusinessLogic attributeBusinessLogic = createTestSubject(); + private IGraphLockOperation igraphLockOperation = Mockito.mock(IGraphLockOperation.class); + + @Before + public void setup() throws Exception { + baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("graphLockOperation"); + baseBusinessLogic.setAccessible(true); + baseBusinessLogic.set(attributeBusinessLogic, igraphLockOperation); + + final Field baseBusinessLogic1 = attributeBusinessLogic.getClass().getSuperclass() + .getDeclaredField("userValidations"); + baseBusinessLogic1.setAccessible(true); + baseBusinessLogic1.set(attributeBusinessLogic, userValidations); + + final Field baseBusinessLogic2 = attributeBusinessLogic.getClass().getSuperclass() + .getDeclaredField("componentsUtils"); + baseBusinessLogic2.setAccessible(true); + baseBusinessLogic2.set(attributeBusinessLogic, componentsUtils); + + final Field baseBusinessLogic3 = attributeBusinessLogic.getClass().getSuperclass() + .getDeclaredField("janusGraphDao"); + baseBusinessLogic3.setAccessible(true); + baseBusinessLogic3.set(attributeBusinessLogic, janusGraphDao); + + baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("toscaOperationFacade"); + baseBusinessLogic.setAccessible(true); + baseBusinessLogic.set(attributeBusinessLogic, toscaOperationFacade); + + baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass() + .getDeclaredField("applicationDataTypeCache"); + baseBusinessLogic.setAccessible(true); + baseBusinessLogic.set(attributeBusinessLogic, applicationDataTypeCache); + + baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("attributeOperation"); + baseBusinessLogic.setAccessible(true); + baseBusinessLogic.set(attributeBusinessLogic, attributeOperation); + } + + @Test + public void createAttribute_lockfail() { + Either response; + response = attributeBusinessLogic.createAttribute("RES01", new AttributeDefinition(), "USR01"); + assertTrue(response.isRight()); + } + + @Test + public void createAttribute_Success() { + Component resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setLastUpdaterUserId("USR01"); + + AttributeDefinition attrib = new AttributeDefinition(); + attrib.setType(ToscaPropertyType.STRING.getType()); + + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + + Either toscastatus = Either.left(resource); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + AttributeDefinition attributeDataDefinition = new AttributeDefinition(); + Either either = Either.left(attributeDataDefinition); + when(toscaOperationFacade.addAttributeOfResource(any(), any())).thenReturn(either); + + when(attributeOperation.isAttributeTypeValid(any())).thenReturn(true); + + Map data = new HashMap<>(); + data.put("ONE", new DataTypeDefinition()); + Either, JanusGraphOperationStatus> allDataTypes = Either.left(data); + when(applicationDataTypeCache.getAll()).thenReturn(allDataTypes); + + when(attributeOperation.isAttributeDefaultValueValid(any(), any())).thenReturn(true); + Either response; + + response = attributeBusinessLogic.createAttribute("RES01", attrib, "USR01"); + + assertTrue(response.isLeft()); + } - AttributeDefinition attrib = new AttributeDefinition(); - attrib.setType(ToscaPropertyType.STRING.getType()); + @Test + public void createAttribute_failtogettoscaelement() throws NoSuchFieldException, IllegalAccessException { + Component resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setLastUpdaterUserId("USR01"); - when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); - - Either toscastatus = Either.left(resource); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - AttributeDataDefinition attributeDataDefinition = new AttributeDataDefinition(); - Either either = Either.left(attributeDataDefinition); - when(toscaOperationFacade.addAttributeOfResource(any(), any())).thenReturn(either); - - when(attributeOperation.isAttributeTypeValid(any())).thenReturn(true); - - Map data = new HashMap<>(); - data.put("ONE", new DataTypeDefinition()); - Either, JanusGraphOperationStatus> allDataTypes = Either.left(data); - when(applicationDataTypeCache.getAll()).thenReturn(allDataTypes); - - when(attributeOperation.isAttributeDefaultValueValid(any(), any())).thenReturn(true); - Either response; - - response = attributeBusinessLogic.createAttribute("RES01", attrib, "USR01"); + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); - assertTrue(response.isLeft()); - } + Either response; + AttributeDefinition prop = new AttributeDefinition(); + + baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("toscaOperationFacade"); + baseBusinessLogic.setAccessible(true); + baseBusinessLogic.set(attributeBusinessLogic, toscaOperationFacade); + Either toscastatus = Either.right(StorageOperationStatus.GENERAL_ERROR); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + + response = attributeBusinessLogic.createAttribute("RES01", prop, "USR01"); - @Test - public void createAttribute_failtogettoscaelement() throws NoSuchFieldException, IllegalAccessException { - Component resource= new Resource(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setIsDeleted(false); - resource.setLastUpdaterUserId("USR01"); + assertTrue(response.isRight()); + } - when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); + @Test + public void createAttribute_componentvalidationfails() { + Component resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); + resource.setIsDeleted(false); + resource.setLastUpdaterUserId("USR02"); - Either response; - AttributeDataDefinition prop= new AttributeDataDefinition(); + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); - baseBusinessLogic = attributeBusinessLogic.getClass().getSuperclass().getDeclaredField("toscaOperationFacade"); - baseBusinessLogic.setAccessible(true); - baseBusinessLogic.set(attributeBusinessLogic, toscaOperationFacade); - Either toscastatus=Either.right(StorageOperationStatus.GENERAL_ERROR); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - - response = attributeBusinessLogic.createAttribute("RES01", prop, "USR01"); + Either response; + AttributeDefinition prop = new AttributeDefinition(); - assertTrue(response.isRight()); - } + Either toscastatus = Either.left(resource); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - @Test - public void createAttribute_componentvalidationfails() { - Component resource= new Resource(); - resource.setLifecycleState(LifecycleStateEnum.CERTIFIED); - resource.setIsDeleted(false); - resource.setLastUpdaterUserId("USR02"); + response = attributeBusinessLogic.createAttribute("RES01", prop, "USR01"); - when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); + assertTrue(response.isRight()); + } - Either response; - AttributeDataDefinition prop= new AttributeDataDefinition(); + @Test + public void createAttribute_componentalreadyexist_fails() { + Either response; + AttributeDefinition attrib = new AttributeDefinition(); + attrib.setName("RES01"); + attrib.setOwnerId("RES01"); - Either toscastatus=Either.left(resource); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + List attributes = new ArrayList<>(); + attributes.add(attrib); - response = attributeBusinessLogic.createAttribute("RES01", prop, "USR01"); + final Resource resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setLastUpdaterUserId("USR01"); + resource.setAttributes(attributes); - assertTrue(response.isRight()); - } + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); - @Test - public void createAttribute_componentalreadyexist_fails() { - Either response; - AttributeDefinition attrib = new AttributeDefinition(); - attrib.setName("RES01"); - attrib.setOwnerId("RES01"); + Either toscastatus = Either.left(resource); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - List attributes = new ArrayList<>(); - attributes.add(attrib); + response = attributeBusinessLogic.createAttribute("RES01", attrib, "USR01"); - final Resource resource = new Resource(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setIsDeleted(false); - resource.setLastUpdaterUserId("USR01"); - resource.setAttributes(attributes); + assertTrue(response.isRight()); + } - when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + @Test + public void createAttribute_addresourcetostoragefails() { - Either toscastatus = Either.left(resource); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + Component resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setLastUpdaterUserId("USR01"); - response = attributeBusinessLogic.createAttribute("RES01", attrib, "USR01"); + IGraphLockOperation igraphLockOperation = Mockito.mock(IGraphLockOperation.class); + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); - assertTrue(response.isRight()); - } + Either toscastatus = Either.left(resource); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + AttributeDefinition attributeDataDefinition = new AttributeDefinition(); + Either either = Either + .right(StorageOperationStatus.CONNECTION_FAILURE); + when(toscaOperationFacade.addAttributeOfResource(any(), any())).thenReturn(either); - @Test - public void createAttribute_addresourcetostoragefails() { + when(attributeOperation.isAttributeTypeValid(any())).thenReturn(true); - Component resource = new Resource(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setIsDeleted(false); - resource.setLastUpdaterUserId("USR01"); + Map data = new HashMap<>(); + data.put("ONE", new DataTypeDefinition()); + Either, JanusGraphOperationStatus> allDataTypes = Either.left(data); + when(applicationDataTypeCache.getAll()).thenReturn(allDataTypes); - IGraphLockOperation igraphLockOperation = Mockito.mock(IGraphLockOperation.class); - when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + when(attributeOperation.isAttributeDefaultValueValid(any(), any())).thenReturn(true); + Either response; - Either toscastatus = Either.left(resource); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - AttributeDataDefinition attributeDataDefinition = new AttributeDataDefinition(); - Either either = Either - .right(StorageOperationStatus.CONNECTION_FAILURE); - when(toscaOperationFacade.addAttributeOfResource(any(),any())).thenReturn(either); + AttributeDefinition attrib = new AttributeDefinition(); + response = attributeBusinessLogic.createAttribute("RES01", attrib, "USR01"); - when(attributeOperation.isAttributeTypeValid(any())).thenReturn(true); + assertTrue(response.isRight()); - Map data = new HashMap<>(); - data.put("ONE", new DataTypeDefinition()); - Either, JanusGraphOperationStatus> allDataTypes = Either.left(data); - when(applicationDataTypeCache.getAll()).thenReturn(allDataTypes); + } - when(attributeOperation.isAttributeDefaultValueValid(any(),any())).thenReturn(true); - Either response; + @Test + public void testgetAttribute_ATTRIBUTE_NOT_FOUND() { + Either result; - AttributeDataDefinition attrib = new AttributeDefinition(); - response = attributeBusinessLogic.createAttribute("RES01", attrib, "USR01"); + Component resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setLastUpdaterUserId("USR01"); + Either toscastatus = Either.left(resource); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - assertTrue( response.isRight()); + result = attributeBusinessLogic.getAttribute("RES01", "ATTR01", "USR01"); + assertTrue(result.isRight()); + } - } + @Test + public void testgetAttribute_success() { + Either result; - @Test - public void testgetAttribute_ATTRIBUTE_NOT_FOUND() { - Either result; + final Resource resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setLastUpdaterUserId("USR01"); - Component resource= new Resource(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setIsDeleted(false); - resource.setLastUpdaterUserId("USR01"); - Either toscastatus=Either.left(resource); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + AttributeDefinition attrib = new AttributeDefinition(); + attrib.setUniqueId("ATTR01"); + attrib.setOwnerId("RES01"); - result=attributeBusinessLogic.getAttribute("RES01","ATTR01", "USR01"); - assertTrue(result.isRight()); - } - - @Test - public void testgetAttribute_success() { - Either result; - - final Resource resource = new Resource(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setIsDeleted(false); - resource.setLastUpdaterUserId("USR01"); - - AttributeDefinition attrib = new AttributeDefinition(); - attrib.setUniqueId("ATTR01"); - attrib.setOwnerId("RES01"); - - List attr = new ArrayList<>(); - attr.add(attrib); - - resource.setAttributes(attr); - Either toscastatus = Either.left(resource); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - - result = attributeBusinessLogic.getAttribute("RES01", "ATTR01", "USR01"); - assertTrue( result.isLeft()); - } - - @Test - public void testgetAttribute_RESOURCE_NOT_FOUND() { - Either result; - - Either toscastatus=Either.right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - - result=attributeBusinessLogic.getAttribute("RES01","ATTR01", "USR01"); - assertTrue(result.isRight()); - } - - @Test - public void testdeleteAttribute_FAILED_TO_LOCK_COMPONENT() { - Either result; - - result=attributeBusinessLogic.deleteAttribute("RES01","ATTR01", "USR01"); - assertTrue(result.isRight()); - } - - @Test - public void testdeleteAttribute_get_RESOURCE_from_DB_failed() { - Either result; - - Either toscastatus=Either.right(StorageOperationStatus.CONNECTION_FAILURE); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - - result=attributeBusinessLogic.deleteAttribute("RES01","ATTR01", "USR01"); - assertTrue(result.isRight()); - } - - @Test - public void testdeleteAttribute_get_RESOURCE_verification_failed() { - Either result; - Component resource= new Resource(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setIsDeleted(true); - resource.setLastUpdaterUserId("USR01"); - when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); - Either toscastatus=Either.left(resource); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - result=attributeBusinessLogic.deleteAttribute("RES01","ATTR01", "USR01"); - assertTrue(result.isRight()); - } - - @Test - public void testdeleteAttribute_nonexistingresource() { - Either result; - - - Component resource= new Resource(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setIsDeleted(false); - resource.setLastUpdaterUserId("USR01"); - - when(igraphLockOperation.lockComponent(any(),any())).thenReturn(StorageOperationStatus.OK); - - Either toscastatus=Either.left(resource); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - - result=attributeBusinessLogic.deleteAttribute("RES01","ATTR01", "USR01"); - assertTrue(result.isRight()); - } - - @Test - public void testdeleteAttribute_success() { - Either result; - final Resource resource = new Resource(); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setIsDeleted(false); - resource.setLastUpdaterUserId("USR01"); - - when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); - - Either toscastatus = Either.left(resource); - when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); - when(toscaOperationFacade.deleteAttributeOfResource(any(), any())).thenReturn(StorageOperationStatus.OK); - - AttributeDefinition attrib = new AttributeDefinition(); - attrib.setUniqueId("ATTR01"); - attrib.setOwnerId("RES01"); - List attributes = new ArrayList<>(); - attributes.add(attrib); - resource.setAttributes(attributes); - - result = attributeBusinessLogic.deleteAttribute("RES01", "ATTR01", "USR01"); - assertTrue( result.isLeft()); - } + List attr = new ArrayList<>(); + attr.add(attrib); + + resource.setAttributes(attr); + Either toscastatus = Either.left(resource); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + + result = attributeBusinessLogic.getAttribute("RES01", "ATTR01", "USR01"); + assertTrue(result.isLeft()); + } + + @Test + public void testgetAttribute_RESOURCE_NOT_FOUND() { + Either result; + + Either toscastatus = Either + .right(StorageOperationStatus.PARENT_RESOURCE_NOT_FOUND); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + + result = attributeBusinessLogic.getAttribute("RES01", "ATTR01", "USR01"); + assertTrue(result.isRight()); + } + + @Test + public void testdeleteAttribute_FAILED_TO_LOCK_COMPONENT() { + Either result; + + result = attributeBusinessLogic.deleteAttribute("RES01", "ATTR01", "USR01"); + assertTrue(result.isRight()); + } + + @Test + public void testdeleteAttribute_get_RESOURCE_from_DB_failed() { + Either result; + + Either toscastatus = Either.right(StorageOperationStatus.CONNECTION_FAILURE); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + + result = attributeBusinessLogic.deleteAttribute("RES01", "ATTR01", "USR01"); + assertTrue(result.isRight()); + } + + @Test + public void testdeleteAttribute_get_RESOURCE_verification_failed() { + Either result; + Component resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(true); + resource.setLastUpdaterUserId("USR01"); + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + Either toscastatus = Either.left(resource); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + result = attributeBusinessLogic.deleteAttribute("RES01", "ATTR01", "USR01"); + assertTrue(result.isRight()); + } + + @Test + public void testdeleteAttribute_nonexistingresource() { + Either result; + + Component resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setLastUpdaterUserId("USR01"); + + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + + Either toscastatus = Either.left(resource); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + + result = attributeBusinessLogic.deleteAttribute("RES01", "ATTR01", "USR01"); + assertTrue(result.isRight()); + } + + @Test + public void testdeleteAttribute_success() { + Either result; + final Resource resource = new Resource(); + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setIsDeleted(false); + resource.setLastUpdaterUserId("USR01"); + + when(igraphLockOperation.lockComponent(any(), any())).thenReturn(StorageOperationStatus.OK); + + Either toscastatus = Either.left(resource); + when(toscaOperationFacade.getToscaElement("RES01")).thenReturn(toscastatus); + when(toscaOperationFacade.deleteAttributeOfResource(any(), any())).thenReturn(StorageOperationStatus.OK); + + AttributeDefinition attrib = new AttributeDefinition(); + attrib.setUniqueId("ATTR01"); + attrib.setOwnerId("RES01"); + List attributes = new ArrayList<>(); + attributes.add(attrib); + resource.setAttributes(attributes); + + result = attributeBusinessLogic.deleteAttribute("RES01", "ATTR01", "USR01"); + assertTrue(result.isLeft()); + } } diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogicTest.java index c176137193..bf51f90165 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceImportBusinessLogicTest.java @@ -52,7 +52,6 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -784,7 +783,7 @@ public class ServiceImportBusinessLogicTest extends ServiceImportBussinessLogicB Map>> instRequirements = new HashMap<>(); Map> instDeploymentArtifacts = new HashMap<>(); Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); Map originCompMap = new HashMap<>(); originCompMap.put("componentUid",originResource); Map> instInputs = new HashMap<>(); @@ -811,7 +810,7 @@ public class ServiceImportBusinessLogicTest extends ServiceImportBussinessLogicB Map>> instRequirements = new HashMap<>(); Map> instDeploymentArtifacts = new HashMap<>(); Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); Map originCompMap = new HashMap<>(); originCompMap.put("componentUid",originResource); Map> instInputs = new HashMap<>(); @@ -1144,7 +1143,7 @@ public class ServiceImportBusinessLogicTest extends ServiceImportBussinessLogicB Map>> instRequirements = new HashMap<>(); Map> instDeploymentArtifacts = new HashMap<>(); Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); Map originCompMap = new HashMap<>(); originCompMap.put("componentUid",originResource); Map> instInputs = new HashMap<>(); @@ -1171,7 +1170,7 @@ public class ServiceImportBusinessLogicTest extends ServiceImportBussinessLogicB Map>> instRequirements = new HashMap<>(); Map> instDeploymentArtifacts = new HashMap<>(); Map> instArtifacts = new HashMap<>(); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); Map originCompMap = new HashMap<>(); originCompMap.put("componentUid",originResource); Map> instInputs = new HashMap<>(); @@ -2381,4 +2380,4 @@ public class ServiceImportBusinessLogicTest extends ServiceImportBussinessLogicB assertThat(expectedResponse.getStatus()).isEqualTo(actualResponse.getStatus()); assertThat(expectedResponse.getFormattedMessage()).isEqualTo(actualResponse.getFormattedMessage()); } -} \ No newline at end of file +} diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogicTest.java index ce57ff103a..8b291e60a0 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ServiceImportParseLogicTest.java @@ -17,12 +17,9 @@ package org.openecomp.sdc.be.components.impl; import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; -import static org.openecomp.sdc.be.auditing.impl.AuditTestUtils.RESOURCE_NAME; import fj.data.Either; import java.io.IOException; @@ -31,17 +28,16 @@ import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; +import java.util.HashMap; import java.util.HashSet; import java.util.List; - +import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.commons.collections.map.HashedMap; import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.MutablePair; import org.junit.Before; import org.junit.Test; -import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -49,36 +45,30 @@ import org.openecomp.sdc.ElementOperationMock; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.components.csar.CsarInfo; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; -import org.openecomp.sdc.be.components.impl.artifact.ArtifactOperationInfo; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; 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.CapabilityDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceInput; import org.openecomp.sdc.be.model.ComponentInstanceProperty; -import org.openecomp.sdc.be.model.ComponentParametersView; -import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.LifecycleStateEnum; import org.openecomp.sdc.be.model.NodeTypeInfo; -import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; import org.openecomp.sdc.be.model.RequirementDefinition; @@ -88,30 +78,22 @@ import org.openecomp.sdc.be.model.UploadCapInfo; import org.openecomp.sdc.be.model.UploadComponentInstanceInfo; import org.openecomp.sdc.be.model.UploadPropInfo; import org.openecomp.sdc.be.model.UploadReqInfo; -import org.openecomp.sdc.be.model.UploadResourceInfo; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.ICapabilityTypeOperation; -import org.openecomp.sdc.be.model.User; - -import java.util.HashMap; -import java.util.Map; - - import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBaseTestSetup { - ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); ServiceBusinessLogic serviceBusinessLogic = Mockito.mock(ServiceBusinessLogic.class); ICapabilityTypeOperation capabilityTypeOperation = Mockito.mock(ICapabilityTypeOperation.class); @@ -289,20 +271,20 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase ArtifactDefinition artifactDefinition = new ArtifactDefinition(); artifactDefinition.setArtifactName("artifactDefinitionName"); vfcArtifacts.add(artifactDefinition); - extractedVfcsArtifacts.put(namespace,vfcArtifacts); + extractedVfcsArtifacts.put(namespace, vfcArtifacts); ImmutablePair p1 = ImmutablePair.of("s", "sd"); Map nodeTypesInfo = new HashedMap(); final Service service = createServiceObject(false); Resource resource = new Resource(); Either getCompLatestResult = Either.left(resource); when(toscaOperationFacade.getLatestByToscaResourceName(anyString())) - .thenReturn(getCompLatestResult); + .thenReturn(getCompLatestResult); try { bl.findAddNodeTypeArtifactsToHandle(getCsarInfo(), nodeTypesArtifactsToHandle, service, - extractedVfcsArtifacts, namespace, p1); + extractedVfcsArtifacts, namespace, p1); } catch (ComponentException e) { assertComponentException(e, ActionStatus.INVALID_TOSCA_TEMPLATE, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -378,7 +360,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase existingArtifact.setArtifactName("ArtifactName"); existingArtifact.setArtifactType("ArtifactType"); existingArtifact.setArtifactChecksum("ArtifactChecksum"); - existingArtifacts.put("existingArtifactMap",existingArtifact); + existingArtifacts.put("existingArtifactMap", existingArtifact); ArtifactDefinition currNewArtifact = new ArtifactDefinition(); currNewArtifact.setArtifactName("ArtifactName"); currNewArtifact.setArtifactType("ArtifactType"); @@ -472,7 +454,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase try { bl.getServiceBusinessLogic().setElementDao(elementDao); - bl.validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE,false, getCsarInfo()); + bl.validateResourceBeforeCreate(resource, user, AuditingActionEnum.IMPORT_RESOURCE, false, getCsarInfo()); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, ComponentTypeEnum.RESOURCE.getValue()); @@ -483,7 +465,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase @Test public void testValidateResourceType() { Resource resource = createParseResourceObject(true); - bl.validateResourceType( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateResourceType(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } @Test @@ -502,7 +484,8 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase interfaceDefinition.setUniqueId(uniqueId); mapInterfaces.put("uniqueId", interfaceDefinition); resource.setInterfaces(mapInterfaces); - when(interfaceTypeOperation.getInterface(anyString())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + when(interfaceTypeOperation.getInterface(anyString())) + .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); bl.validateLifecycleTypesCreate(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } @@ -511,7 +494,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Resource resource = createParseResourceObject(true); Map> capabilities = new HashMap<>(); String uniqueId = "18982938994"; - List capabilityDefinitionList= new ArrayList<>(); + List capabilityDefinitionList = new ArrayList<>(); CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); capabilityDefinitionList.add(capabilityDefinition); capabilities.put(uniqueId, capabilityDefinitionList); @@ -532,7 +515,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Resource resource = createParseResourceObject(true); Map> capabilities = new HashMap<>(); String uniqueId = "18982938994"; - List capabilityDefinitionList= new ArrayList<>(); + List capabilityDefinitionList = new ArrayList<>(); CapabilityDefinition capabilityDefinition = new CapabilityDefinition(); capabilityDefinitionList.add(capabilityDefinition); capabilities.put(uniqueId, capabilityDefinitionList); @@ -605,7 +588,6 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Map> capabilities = new HashMap<>(); - List capabilityDefinitionList = new ArrayList<>(); List componentInstancePropertyList = new ArrayList<>(); ComponentInstanceProperty componentInstanceProperty = new ComponentInstanceProperty(); @@ -619,7 +601,6 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase capabilities.put(uniqueId, capabilityDefinitionList); resource.setCapabilities(capabilities); - when(capabilityTypeOperation.getCapabilityType(anyString(), anyBoolean())). thenReturn(Either.left(capabilityTypeDefinition)); for (Map.Entry> typeEntry : resource.getCapabilities().entrySet()) { @@ -654,7 +635,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testValidateResourceFieldsBeforeCreate() { Resource resource = createParseResourceObject(true); try { - bl.validateResourceFieldsBeforeCreate( user, resource, AuditingActionEnum.IMPORT_RESOURCE, true); + bl.validateResourceFieldsBeforeCreate(user, resource, AuditingActionEnum.IMPORT_RESOURCE, true); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, ComponentTypeEnum.RESOURCE.getValue()); @@ -667,7 +648,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase try { when(toscaOperationFacade.validateToscaResourceNameExists(anyString())) .thenReturn(Either.left(true)); - bl.validateDerivedFromExist( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateDerivedFromExist(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, ComponentTypeEnum.RESOURCE.getValue()); @@ -680,7 +661,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase try { when(toscaOperationFacade.validateToscaResourceNameExists(anyString())) .thenReturn(Either.left(false)); - bl.validateDerivedFromExist( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateDerivedFromExist(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { assertComponentException(e, ActionStatus.PARENT_RESOURCE_NOT_FOUND, ComponentTypeEnum.RESOURCE.getValue()); @@ -693,7 +674,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase try { when(toscaOperationFacade.validateToscaResourceNameExists(anyString())) .thenReturn(Either.right(StorageOperationStatus.OK)); - bl.validateDerivedFromExist( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateDerivedFromExist(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { assertComponentException(e, ActionStatus.OK, ComponentTypeEnum.RESOURCE.getValue()); @@ -705,7 +686,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Resource resource = createParseResourceObject(true); try { - bl.validateLicenseType( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateLicenseType(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { assertComponentException(e, ActionStatus.INVALID_CONTENT, ComponentTypeEnum.RESOURCE.getValue()); @@ -718,7 +699,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testValidateCost() { Resource resource = createParseResourceObject(true); try { - bl.validateCost( resource); + bl.validateCost(resource); } catch (ComponentException e) { assertComponentException(e, ActionStatus.INVALID_CONTENT, ComponentTypeEnum.RESOURCE.getValue()); @@ -728,7 +709,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase @Test public void testValidateResourceVendorModelNumber() { Resource resource = createParseResourceObject(true); - bl.validateResourceVendorModelNumber( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateResourceVendorModelNumber(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } @Test @@ -736,7 +717,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Resource resource = createParseResourceObject(true); resource.setResourceVendorModelNumber("000000000011122221111222333444443222556677788778889999998776554332340"); try { - bl.validateResourceVendorModelNumber( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateResourceVendorModelNumber(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { e.printStackTrace(); } @@ -747,7 +728,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Resource resource = createParseResourceObject(true); resource.setResourceVendorModelNumber(""); try { - bl.validateResourceVendorModelNumber( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateResourceVendorModelNumber(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { assertComponentException(e, ActionStatus.INVALID_RESOURCE_VENDOR_MODEL_NUMBER, ComponentTypeEnum.RESOURCE.getValue()); @@ -758,7 +739,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testValidateVendorReleaseName() { Resource resource = createParseResourceObject(true); resource.setVendorRelease("0.1"); - bl.validateVendorReleaseName( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateVendorReleaseName(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } @Test @@ -766,7 +747,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Resource resource = createParseResourceObject(true); resource.setVendorRelease(""); try { - bl.validateVendorReleaseName( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateVendorReleaseName(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { assertComponentException(e, ActionStatus.MISSING_VENDOR_RELEASE, ComponentTypeEnum.RESOURCE.getValue()); @@ -789,7 +770,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testValidateCategory() { Resource resource = createParseResourceObject(true); try { - bl.validateCategory( user, resource, AuditingActionEnum.IMPORT_RESOURCE, true); + bl.validateCategory(user, resource, AuditingActionEnum.IMPORT_RESOURCE, true); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, ComponentTypeEnum.RESOURCE.getValue()); @@ -898,7 +879,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase CategoryDefinition category = resource.getCategories().get(0); SubCategoryDefinition subcategory = category.getSubcategories().get(0); try { - bl.validateCategoryListed( category, subcategory, user, resource, AuditingActionEnum.IMPORT_RESOURCE, true); + bl.validateCategoryListed(category, subcategory, user, resource, AuditingActionEnum.IMPORT_RESOURCE, true); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, ComponentTypeEnum.RESOURCE.getValue()); @@ -909,7 +890,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testFailOnInvalidCategory() { Resource resource = createParseResourceObject(true); try { - bl.failOnInvalidCategory( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.failOnInvalidCategory(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { assertComponentException(e, ActionStatus.COMPONENT_INVALID_CATEGORY, ComponentTypeEnum.RESOURCE.getValue()); @@ -921,7 +902,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testValidateVendorName() { Resource resource = createParseResourceObject(true); try { - bl.validateVendorName( user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateVendorName(user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, ComponentTypeEnum.RESOURCE.getValue()); @@ -950,6 +931,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase e.printStackTrace(); } } + @Test public void testValidateVendorName2() { Resource resource = createParseResourceObject(true); @@ -957,7 +939,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase SubCategoryDefinition subcategory = category.getSubcategories().get(0); String vendorName = "vendorName"; try { - bl.validateVendorName( vendorName, user, resource, AuditingActionEnum.IMPORT_RESOURCE); + bl.validateVendorName(vendorName, user, resource, AuditingActionEnum.IMPORT_RESOURCE); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, ComponentTypeEnum.RESOURCE.getValue()); @@ -971,7 +953,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "test"; resourceVf.setSystemName("systemName"); try { - bl.fillResourceMetadata( yamlName, resourceVf, nodeName, user); + bl.fillResourceMetadata(yamlName, resourceVf, nodeName, user); } catch (ComponentException e) { e.printStackTrace(); } @@ -1004,7 +986,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase @Test public void testGetNodeTypeActualName() { - String fullName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX+"test"; + String fullName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "test"; try { bl.getNodeTypeActualName(fullName); } catch (ComponentException e) { @@ -1144,7 +1126,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase @Test public void testGetComponentWithInstancesFilter() { - try { + try { bl.getComponentWithInstancesFilter(); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, @@ -1172,7 +1154,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase InputDefinition prop = new InputDefinition(); Resource resource = createParseResourceObject(true); - Map> capabilitiesMap = resource.getCapabilities(); + Map> capabilitiesMap = resource.getCapabilities(); capabilitiesMap.put(key, capabilityDefinitionList); when(toscaOperationFacade.getToscaFullElement(anyString())) @@ -1288,10 +1270,10 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Map artifactMap = new HashMap<>(); String k = "key"; Object v = new Object(); - Map> artifactDetails = new HashMap<>(); + Map> artifactDetails = new HashMap<>(); List artifactTypes = new ArrayList<>(); artifactTypes.add(ResourceTypeEnum.VF.name()); - artifactDetails.put("validForResourceTypes",artifactTypes); + artifactDetails.put("validForResourceTypes", artifactTypes); v = artifactDetails; bl.processDeploymentResourceArtifacts(user, resource, artifactMap, k, v); @@ -1348,7 +1330,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase try { bl.createInputsOnResource(resource, inputs); - } catch (ComponentException e) { + } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, ComponentTypeEnum.RESOURCE.getValue()); } @@ -1382,7 +1364,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Map inputs = new HashMap<>(); InputDefinition inputDefinitionMap = new InputDefinition(); inputDefinition.setName("inputDefinitionName"); - inputs.put("inputsMap",inputDefinitionMap); + inputs.put("inputsMap", inputDefinitionMap); try { bl.createInputsOnService(service, inputs); @@ -1515,14 +1497,14 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase } } - @Test + @Test public void testFailOnChangeState() { ResponseFormat response = new ResponseFormat(); Resource oldResource = createParseResourceObject(true); Resource newResource = createParseResourceObject(true); try { - bl.failOnChangeState(response, user, oldResource, newResource); + bl.failOnChangeState(response, user, oldResource, newResource); } catch (Exception e) { e.printStackTrace(); } @@ -1535,7 +1517,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase try { bl.handleResourceGenericType(resource); } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); } } @@ -1558,7 +1540,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase groupDefinition.setInvariantName("groupDefinitionName"); groupsFromResource.add(groupDefinition); List groupsAsList = new ArrayList<>(); - GroupDefinition groupNewDefinition =getGroupDefinition(); + GroupDefinition groupNewDefinition = getGroupDefinition(); groupsAsList.add(groupNewDefinition); List groupsToUpdate = new ArrayList<>(); List groupsToCreate = new ArrayList<>(); @@ -1587,7 +1569,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase Map groups = new HashMap<>(); GroupDefinition groupDefinition = getGroupDefinition(); groupDefinition.setMembers(null); - groups.put("groupsMap",groupDefinition); + groups.put("groupsMap", groupDefinition); bl.updateGroupsMembersUsingResource(groups, component); } @@ -1688,7 +1670,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testFillResourceMetadataForServiceWrongType() { String yamlName = "yamlName"; Service resourceVf = createServiceObject(true); - String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX+"nodeName"; + String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "nodeName"; try { bl.fillResourceMetadata(yamlName, resourceVf, nodeName, user); @@ -1701,7 +1683,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testFillResourceMetadataForServiceSuccess() { String yamlName = "yamlName"; Service resourceVf = createServiceObject(true); - String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX+"VFC"; + String nodeName = Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX + "VFC"; try { bl.fillResourceMetadata(yamlName, resourceVf, nodeName, user); @@ -1787,7 +1769,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase List nodeTypesNewCreatedArtifacts = new ArrayList<>(); try { - bl.rollback(false,resource, createdArtifacts,nodeTypesNewCreatedArtifacts); + bl.rollback(false, resource, createdArtifacts, nodeTypesNewCreatedArtifacts); } catch (Exception e) { e.printStackTrace(); } @@ -1827,12 +1809,12 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.handleGroupsProperties(service, groups); } - @Test + @Test public void testHandleGroupsProperties2() { Resource resource = createParseResourceObject(true); Map groups = getGroups(); - bl.handleGroupsProperties(resource, groups); + bl.handleGroupsProperties(resource, groups); } @Test @@ -1897,7 +1879,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateComponentInstancePropertiesToComponent(yamlName, resource, instProperties); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -1924,7 +1906,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -1938,7 +1920,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateDeploymentArtifactsToInstances(user, yamlName, resource, instDeploymentArtifacts); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -1952,7 +1934,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateArtifactsToInstances(yamlName, resource, instDeploymentArtifacts); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -1966,7 +1948,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -1974,12 +1956,12 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testAssociateInstAttributeToComponentToInstances() { String yamlName = "yamlName"; Resource resource = createParseResourceObject(true); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); try { bl.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -1991,7 +1973,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.throwComponentExceptionByResource(status, resource); } catch (ComponentException e) { assertComponentException(e, ActionStatus.OK, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -2001,7 +1983,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase try { bl.getResourceAfterCreateRelations(resource); - } catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -2014,12 +1996,12 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase capabilityDefinition.setName("Capability"); capabilityDefinition.setType("Resource"); capabilityDefinitionList.add(capabilityDefinition); - originCapabilities.put("Capability",capabilityDefinitionList); + originCapabilities.put("Capability", capabilityDefinitionList); Map> uploadedCapabilities = new HashMap<>(); List uploadCapInfoList = new ArrayList<>(); UploadCapInfo uploadCapInfo = new UploadCapInfo(); uploadCapInfoList.add(uploadCapInfo); - uploadedCapabilities.put("Capability",uploadCapInfoList); + uploadedCapabilities.put("Capability", uploadCapInfoList); bl.setCapabilityNamesTypes(originCapabilities, uploadedCapabilities); } @@ -2034,7 +2016,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateComponentInstanceInputsToComponent(yamlName, service, instInputs); } catch (ComponentException e) { assertComponentException(e, ActionStatus.OK, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -2061,7 +2043,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateDeploymentArtifactsToInstances(user, yamlName, service, instDeploymentArtifacts); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -2075,9 +2057,10 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateArtifactsToInstances(yamlName, service, instArtifacts); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } + @Test public void testAssociateOrAddCalculatedCapReq2() { String yamlName = "yamlName"; @@ -2088,7 +2071,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateOrAddCalculatedCapReq(yamlName, resource, instCapabilities, instRequirements); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -2096,12 +2079,12 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase public void testAssociateInstAttributeToComponentToInstances2() { String yamlName = "yamlName"; Service resource = createServiceObject(true); - Map> instAttributes = new HashMap<>(); + Map> instAttributes = new HashMap<>(); try { bl.associateInstAttributeToComponentToInstances(yamlName, resource, instAttributes); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -2114,7 +2097,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateRequirementsToService(yamlName, resource, requirements); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -2127,7 +2110,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase bl.associateCapabilitiesToService(yamlName, resource, capabilities); } catch (ComponentException e) { assertComponentException(e, ActionStatus.GENERAL_ERROR, - ComponentTypeEnum.RESOURCE.getValue()); + ComponentTypeEnum.RESOURCE.getValue()); } } @@ -2139,7 +2122,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase try { bl.associateResourceInstances(yamlName, resource, relations); } catch (Exception e) { - e.printStackTrace(); + e.printStackTrace(); } } @@ -2217,7 +2200,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase } @Test - public void testAddRelationsToRI_null(){ + public void testAddRelationsToRI_null() { String yamlName = "group.yml"; Resource resource = createParseResourceObject(true); Map uploadResInstancesMap = new HashMap<>(); @@ -2227,8 +2210,8 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase List relations = new ArrayList<>(); try { - bl.addRelationsToRI(yamlName,resource,uploadResInstancesMap,componentInstancesList, - relations); + bl.addRelationsToRI(yamlName, resource, uploadResInstancesMap, componentInstancesList, + relations); } catch (Exception e) { e.printStackTrace(); } @@ -2239,14 +2222,14 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase String yamlName = "yamlName"; Resource resource = createParseResourceObject(true); resource.setComponentInstances(creatComponentInstances()); - UploadComponentInstanceInfo nodesInfoValue =getuploadComponentInstanceInfo(); + UploadComponentInstanceInfo nodesInfoValue = getuploadComponentInstanceInfo(); List relations = new ArrayList<>(); bl.addRelationToRI(yamlName, resource, nodesInfoValue, relations); } @Test - public void testAddRelationToRI_null(){ + public void testAddRelationToRI_null() { String yamlName = "yamlName.yml"; Resource resource = createParseResourceObject(false); List componentInstancesList = new ArrayList<>(); @@ -2273,7 +2256,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase } } - protected GroupDefinition getGroupDefinition(){ + protected GroupDefinition getGroupDefinition() { GroupDefinition groupDefinition = new GroupDefinition(); Map members = new HashMap<>(); members.put("members", "members"); @@ -2310,7 +2293,6 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase resource.setCost("cost"); resource.setResourceVendorModelNumber("02312233"); - Map artifacts = new HashMap<>(); ArtifactDefinition artifactDefinition = new ArtifactDefinition(); artifacts.put("artifact", artifactDefinition); @@ -2358,7 +2340,7 @@ public class ServiceImportParseLogicTest extends ServiceImportBussinessLogicBase return new String(fileContent); } - protected Service createServiceObject (boolean afterCreate) { + protected Service createServiceObject(boolean afterCreate) { Service service = new Service(); service.setUniqueId("sid"); service.setName("Service"); diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java index 79c2ec460f..8697f6643a 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/jsongraph/types/VertexTypeEnum.java @@ -34,6 +34,7 @@ import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; import org.openecomp.sdc.be.datatypes.elements.MapComponentInstanceExternalRefs; import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; @@ -69,7 +70,7 @@ public enum VertexTypeEnum { USER ("user", null), INPUTS ("inputs", PropertyDataDefinition.class), GROUPS ("groups", GroupDataDefinition.class), - INST_ATTRIBUTES ("instAttributes", MapPropertiesDataDefinition.class), + INST_ATTRIBUTES ("instAttributes", MapAttributesDataDefinition.class), INST_PROPERTIES ("instProperties", MapPropertiesDataDefinition.class), INST_INPUTS ("instInputs", MapPropertiesDataDefinition.class), INST_GROUPS ("instGroups", MapGroupsDataDefinition.class), diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java index 20ad0ad01f..f9e0d646b3 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/AttributeDefinition.java @@ -42,6 +42,10 @@ public class AttributeDefinition extends AttributeDataDefinition implements IOpe toscaPresentation = null; } + public AttributeDefinition(final AttributeDataDefinition attributeDataDefinition) { + super(attributeDataDefinition); + } + public AttributeDefinition(final AttributeDefinition attributeDefinition) { this.type = attributeDefinition.getType(); this.description = attributeDefinition.getDescription(); @@ -52,7 +56,7 @@ public class AttributeDefinition extends AttributeDataDefinition implements IOpe @Override public String getDefaultValue() { - return String.valueOf(_default); + return _default == null ? null : String.valueOf(_default); } @Override diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java index 64660ec15f..600451d193 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Component.java @@ -64,6 +64,7 @@ public abstract class Component implements PropertiesOwner { protected List additionalInformation; protected List properties; + protected List attributes; private ComponentMetadataDefinition componentMetadataDefinition; private Map artifacts; private Map deploymentArtifacts; @@ -73,6 +74,7 @@ public abstract class Component implements PropertiesOwner { private List componentInstances; private List componentInstancesRelations; private Map> componentInstancesInputs; + private Map> componentInstancesOutputs; private Map> componentInstancesProperties; private Map> componentInstancesAttributes; private Map> capabilities; @@ -100,7 +102,7 @@ public abstract class Component implements PropertiesOwner { return categorySpecificMetadata == null ? Collections.emptyMap() : categorySpecificMetadata; } - public Component(ComponentMetadataDefinition componentMetadataDefinition) { + protected Component(ComponentMetadataDefinition componentMetadataDefinition) { this.componentMetadataDefinition = componentMetadataDefinition; } @@ -329,18 +331,18 @@ public abstract class Component implements PropertiesOwner { public Map safeGetComponentInstanceDeploymentArtifacts(String componentInstanceId) { return getComponentInstanceById(componentInstanceId).map(ComponentInstance::safeGetDeploymentArtifacts) - .orElse(emptyMap()); + .orElse(emptyMap()); } public Map safeGetComponentInstanceInformationalArtifacts(String componentInstanceId) { return getComponentInstanceById(componentInstanceId).map(ComponentInstance::safeGetInformationalArtifacts) - .orElse(emptyMap()); + .orElse(emptyMap()); } public List safeGetComponentInstanceHeatArtifacts(String componentInstanceId) { return safeGetComponentInstanceDeploymentArtifacts(componentInstanceId).values().stream() - .filter(artifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(artifact.getArtifactType())) - .collect(Collectors.toList()); + .filter(artifact -> ArtifactTypeEnum.HEAT_ENV.getType().equals(artifact.getArtifactType())) + .collect(Collectors.toList()); } public Map> safeGetComponentInstancesProperties() { @@ -353,9 +355,9 @@ public abstract class Component implements PropertiesOwner { private Map> findUiComponentInstancesProperties() { List instancesFromUi = componentInstances.stream().filter(i -> !i.isCreatedFromCsar()) - .map(ComponentInstance::getUniqueId).collect(Collectors.toList()); + .map(ComponentInstance::getUniqueId).collect(Collectors.toList()); return componentInstancesProperties.entrySet().stream().filter(e -> instancesFromUi.contains(e.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } public Map> safeGetComponentInstancesInputs() { @@ -368,9 +370,9 @@ public abstract class Component implements PropertiesOwner { private Map> findUiComponentInstancesInputs() { List instancesFromUi = componentInstances.stream().filter(i -> !i.isCreatedFromCsar()) - .map(ComponentInstance::getUniqueId).collect(Collectors.toList()); + .map(ComponentInstance::getUniqueId).collect(Collectors.toList()); return componentInstancesInputs.entrySet().stream().filter(e -> instancesFromUi.contains(e.getKey())) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } public List safeGetComponentInstanceProperties(String cmptInstacneId) { @@ -491,7 +493,7 @@ public abstract class Component implements PropertiesOwner { this.properties = new ArrayList<>(); } - this.properties.add(propertyDefinition);; + this.properties.add(propertyDefinition); } public void addCategory(String category, String subCategory) { @@ -573,7 +575,7 @@ public abstract class Component implements PropertiesOwner { return emptyMap(); } return groups.stream().filter(gr -> Objects.nonNull(gr.getProperties())) - .collect(toMap(GroupDataDefinition::getUniqueId, GroupDataDefinition::getProperties)); + .collect(toMap(GroupDataDefinition::getUniqueId, GroupDataDefinition::getProperties)); } public Map> safeGetPolicyProperties() { @@ -581,7 +583,7 @@ public abstract class Component implements PropertiesOwner { return emptyMap(); } return policies.values().stream().filter(policy -> Objects.nonNull(policy.getProperties())) - .collect(toMap(PolicyDataDefinition::getUniqueId, PolicyDataDefinition::getProperties)); + .collect(toMap(PolicyDataDefinition::getUniqueId, PolicyDataDefinition::getProperties)); } public List safeGetComponentInstanceInputsByName(String cmptInstanceName) { @@ -590,9 +592,9 @@ public abstract class Component implements PropertiesOwner { return emptyPropsList; } return this.componentInstances.stream().filter(ci -> ci.getName().equals(cmptInstanceName)) - .map(ComponentInstance::getUniqueId) - .map(instanceId -> safeGetComponentInstanceEntity(instanceId, this.componentInstancesInputs)).findAny() - .orElse(emptyPropsList); + .map(ComponentInstance::getUniqueId) + .map(instanceId -> safeGetComponentInstanceEntity(instanceId, this.componentInstancesInputs)).findAny() + .orElse(emptyPropsList); } private List safeGetComponentInstanceEntity(String cmptInstanceId, Map> instanceEntities) { @@ -610,7 +612,7 @@ public abstract class Component implements PropertiesOwner { public String fetchGenericTypeToscaNameFromConfig() { return ConfigurationManager.getConfigurationManager().getConfiguration().getGenericAssetNodeTypes() - .get(this.assetType()); + .get(this.assetType()); } protected Optional getHeadOption(List list) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java index 0057b71a27..dd8296e8f7 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstance.java @@ -30,7 +30,6 @@ import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner; -import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterDataDefinition; import org.openecomp.sdc.be.datatypes.enums.CreatedFrom; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.log.api.ILogConfiguration; @@ -46,6 +45,7 @@ public class ComponentInstance extends ComponentInstanceDataDefinition implement private List groupInstances; private Map interfaces; private List properties; + private List attributes; private CINodeFilterDataDefinition nodeFilter; private List inputs; diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java index 6583bf46c4..af2964ff40 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceAttribute.java @@ -28,9 +28,10 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyRule; @Getter @Setter -public class ComponentInstanceAttribute extends AttributeDefinition implements IComponentInstanceConnectedElement, IAttributeInputCommon { +public class ComponentInstanceAttribute extends AttributeDefinition implements IComponentInstanceConnectedElement, IAttributeOutputCommon { public ComponentInstanceAttribute(final AttributeDataDefinition value) { + super(value); } public ComponentInstanceAttribute() { super(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceOutput.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceOutput.java new file mode 100644 index 0000000000..db79511a67 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentInstanceOutput.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2021, Nordix Foundation. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model; + +import java.util.List; +import lombok.Getter; +import lombok.Setter; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyRule; + +@Getter +@Setter +public class ComponentInstanceOutput extends OutputDefinition implements IComponentInstanceConnectedElement, IAttributeOutputCommon { + + /** + * The unique id of the attribute value on graph + */ + private String valueUniqueUid; + + private List path = null; + + private List rules = null; + private String componentInstanceName; + private String componentInstanceId; + + public ComponentInstanceOutput(AttributeDataDefinition curPropertyDef, String outputId, String value, + String valueUniqueUid) { + super(curPropertyDef); + setOutputId(outputId); + setValue(value); + this.valueUniqueUid = valueUniqueUid; + } + + public ComponentInstanceOutput(OutputDefinition pd, String value, String valueUniqueUid) { + super(pd); + + setValue(value); + this.valueUniqueUid = valueUniqueUid; + } + + public ComponentInstanceOutput(AttributeDataDefinition attributeDataDefinition) { + super(attributeDataDefinition); + if (attributeDataDefinition.getGetOutputValues() != null && !attributeDataDefinition.getGetOutputValues() + .isEmpty()) { + setOutputId(attributeDataDefinition.getGetOutputValues().get(0).getInputId()); + } + } + + @Override + public String toString() { + return "ComponentInstanceOutput [ " + super.toString() + " , value=" + getValue() + ", valueUniqueUid = " + + valueUniqueUid + " , rules=" + rules + " , path=" + path + " ]"; + } + +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java index 6488d41f25..87917d7861 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/ComponentParametersView.java @@ -21,17 +21,25 @@ package org.openecomp.sdc.be.model; import java.util.List; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +@Getter +@Setter +@NoArgsConstructor public class ComponentParametersView { private boolean ignoreUsers = false; private boolean ignoreGroups = false; private boolean ignoreComponentInstances = false; private boolean ignoreComponentInstancesProperties = false; + private boolean ignoreComponentInstancesAttributes = false; private boolean ignoreProperties = false; + private boolean ignoreAttributes = false; private boolean ignoreCapabilities = false; private boolean ignoreRequirements = false; private boolean ignoreCategories = false; @@ -42,10 +50,10 @@ public class ComponentParametersView { private boolean ignoreInterfaceInstances = false; private boolean ignoreComponentInstancesInterfaces = false; private boolean ignoreDerivedFrom = false; - private boolean ignoreAttributesFrom = false; - private boolean ignoreComponentInstancesAttributesFrom = false; private boolean ignoreInputs = false; + private boolean ignoreOutputs = false; private boolean ignoreComponentInstancesInputs = false; + private boolean ignoreComponentInstancesOutputs = false; private boolean ignoreCapabiltyProperties = false; private boolean ignoreServicePath = true; private boolean ignorePolicies = false; @@ -54,9 +62,6 @@ public class ComponentParametersView { private boolean ignoreSubstitutionFilter = false; private boolean ignoreDataType = false; - public ComponentParametersView() { - } - public ComponentParametersView(boolean setAllToIgnore) { this(); if (setAllToIgnore) { @@ -75,6 +80,9 @@ public class ComponentParametersView { case INPUTS: this.setIgnoreInputs(false); break; + case OUTPUTS: + this.setIgnoreOutputs(false); + break; case USERS: this.setIgnoreUsers(false); break; @@ -133,11 +141,11 @@ public class ComponentParametersView { this.setIgnoreDerivedFrom(false); break; case ATTRIBUTES: - this.setIgnoreAttributesFrom(false); + this.setIgnoreAttributes(false); break; case COMPONENT_INSTANCES_ATTRIBUTES: this.setIgnoreComponentInstances(false); - this.setIgnoreComponentInstancesAttributesFrom(false); + this.setIgnoreComponentInstancesAttributes(false); break; case COMPONENT_INSTANCE_INPUTS: this.setIgnoreComponentInstances(false); @@ -147,7 +155,7 @@ public class ComponentParametersView { this.setIgnoreCapabiltyProperties(false); break; case FORWARDING_PATHS: - this.setIgnoreForwardingPath(false); + this.setIgnoreServicePath(false); break; case POLICIES: case NON_EXCLUDED_POLICIES: @@ -178,7 +186,6 @@ public class ComponentParametersView { /////////////////////////////////////////////////////////////// // When adding new member, please update the filter method. /////////////////////////////////////////////////////////////// - public Component filter(Component component, ComponentTypeEnum componentType) { if (ignoreUsers) { @@ -200,6 +207,9 @@ public class ComponentParametersView { if (ignoreProperties && componentType == ComponentTypeEnum.RESOURCE) { ((Resource) component).setProperties(null); } + if (ignoreAttributes) { + component.setAttributes(null); + } if (ignoreCapabilities) { component.setCapabilities(null); } @@ -221,8 +231,8 @@ public class ComponentParametersView { component.setDeploymentArtifacts(null); component.setToscaArtifacts(null); } - if (ignoreNodeFilterRequirements){ - component.setNodeFilterComponents(null); + if (ignoreNodeFilterRequirements) { + component.setNodeFilterComponents(null); } if (ignoreInterfaces && ignoreInterfaceInstances && componentType == ComponentTypeEnum.RESOURCE) { @@ -231,25 +241,28 @@ public class ComponentParametersView { if (ignoreDerivedFrom && componentType == ComponentTypeEnum.RESOURCE) { ((Resource) component).setDerivedFrom(null); } - if (ignoreAttributesFrom && componentType == ComponentTypeEnum.RESOURCE) { - ((Resource) component).setAttributes(null); - } - if (ignoreComponentInstancesAttributesFrom) { + if (ignoreComponentInstancesAttributes) { component.setComponentInstancesAttributes(null); } if (ignoreInputs) { component.setInputs(null); } + if (ignoreOutputs) { + component.setOutputs(null); + } if (ignoreComponentInstancesInputs) { component.setComponentInstancesInputs(null); } + if (ignoreComponentInstancesOutputs) { + component.setComponentInstancesOutputs(null); + } if (ignoreServicePath && componentType == ComponentTypeEnum.SERVICE) { ((Service) component).setForwardingPaths(null); } - if (ignoreNodeFilter){ + if (ignoreNodeFilter) { component.setNodeFilterComponents(null); } - if (ignoreSubstitutionFilter){ + if (ignoreSubstitutionFilter) { component.setSubstitutionFilterComponents(null); } if (ignoreDataType) { @@ -258,14 +271,6 @@ public class ComponentParametersView { return component; } - public boolean isIgnoreNodeFilterRequirements() { - return ignoreNodeFilterRequirements; - } - - public void setIgnoreNodeFilterRequirements(boolean ignoreNodeFilter) { - this.ignoreNodeFilterRequirements = ignoreNodeFilter; - } - public void disableAll() { ignoreUsers = true; ignoreGroups = true; @@ -273,6 +278,7 @@ public class ComponentParametersView { ignoreComponentInstances = true; ignoreComponentInstancesProperties = true; ignoreProperties = true; + ignoreAttributes = true; ignoreCapabilities = true; ignoreRequirements = true; ignoreCategories = true; @@ -282,10 +288,11 @@ public class ComponentParametersView { ignoreInterfaces = true; ignoreInterfaceInstances = true; ignoreDerivedFrom = true; - ignoreAttributesFrom = true; ignoreInputs = true; - ignoreComponentInstancesAttributesFrom = true; + ignoreOutputs = true; + ignoreComponentInstancesAttributes = true; ignoreComponentInstancesInputs = true; + ignoreComponentInstancesOutputs = true; ignoreCapabiltyProperties = true; ignoreServicePath = true; ignoreNodeFilterRequirements = true; @@ -294,10 +301,6 @@ public class ComponentParametersView { ignoreDataType = true; } - public boolean isIgnoreGroups() { - return ignoreGroups; - } - public void setIgnoreGroups(boolean ignoreGroups) { this.ignoreGroups = ignoreGroups; if (!ignoreGroups) { @@ -306,190 +309,6 @@ public class ComponentParametersView { } } - public boolean isIgnoreComponentInstances() { - return ignoreComponentInstances; - } - - public void setIgnoreComponentInstances(boolean ignoreComponentInstances) { - this.ignoreComponentInstances = ignoreComponentInstances; - } - - public boolean isIgnoreProperties() { - return ignoreProperties; - } - - public void setIgnoreProperties(boolean ignoreProperties) { - this.ignoreProperties = ignoreProperties; - } - - public boolean isIgnoreCapabilities() { - return ignoreCapabilities; - } - - public void setIgnoreCapabilities(boolean ignoreCapabilities) { - this.ignoreCapabilities = ignoreCapabilities; - } - - public boolean isIgnoreRequirements() { - return ignoreRequirements; - } - - public void setIgnoreRequirements(boolean ignoreRequirements) { - this.ignoreRequirements = ignoreRequirements; - } - - public boolean isIgnoreCategories() { - return ignoreCategories; - } - - public void setIgnoreCategories(boolean ignoreCategories) { - this.ignoreCategories = ignoreCategories; - } - - public boolean isIgnoreAllVersions() { - return ignoreAllVersions; - } - - public void setIgnoreAllVersions(boolean ignoreAllVersions) { - this.ignoreAllVersions = ignoreAllVersions; - } - - public boolean isIgnoreAdditionalInformation() { - return ignoreAdditionalInformation; - } - - private void setIgnoreAdditionalInformation(boolean ignoreAdditionalInformation) { - this.ignoreAdditionalInformation = ignoreAdditionalInformation; - } - - public boolean isIgnoreArtifacts() { - return ignoreArtifacts; - } - - public void setIgnoreArtifacts(boolean ignoreArtifacts) { - this.ignoreArtifacts = ignoreArtifacts; - } - - public boolean isIgnoreComponentInstancesProperties() { - return ignoreComponentInstancesProperties; - } - - public void setIgnoreComponentInstancesProperties(boolean ignoreComponentInstancesProperties) { - this.ignoreComponentInstancesProperties = ignoreComponentInstancesProperties; - } - - public boolean isIgnoreComponentInstancesInputs() { - return ignoreComponentInstancesInputs; - } - - public void setIgnoreComponentInstancesInputs(boolean ignoreComponentInstancesInputs) { - this.ignoreComponentInstancesInputs = ignoreComponentInstancesInputs; - } - - public boolean isIgnoreInterfaces() { - return ignoreInterfaces; - } - - public void setIgnoreInterfaces(boolean ignoreInterfaces) { - this.ignoreInterfaces = ignoreInterfaces; - } - - public boolean isIgnoreComponentInstancesInterfaces() { - return ignoreComponentInstancesInterfaces; - } - - public void setIgnoreComponentInstancesInterfaces(boolean ignoreComponentInstancesInterfaces) { - this.ignoreComponentInstancesInterfaces = ignoreComponentInstancesInterfaces; - } - - public boolean isIgnoreAttributesFrom() { - return ignoreAttributesFrom; - } - - public void setIgnoreAttributesFrom(boolean ignoreAttributesFrom) { - this.ignoreAttributesFrom = ignoreAttributesFrom; - } - - public boolean isIgnoreComponentInstancesAttributesFrom() { - return ignoreComponentInstancesAttributesFrom; - } - - private void setIgnoreComponentInstancesAttributesFrom(boolean ignoreComponentInstancesAttributesFrom) { - this.ignoreComponentInstancesAttributesFrom = ignoreComponentInstancesAttributesFrom; - } - - public boolean isIgnoreDerivedFrom() { - return ignoreDerivedFrom; - } - - private void setIgnoreDerivedFrom(boolean ignoreDerivedFrom) { - this.ignoreDerivedFrom = ignoreDerivedFrom; - } - - public boolean isIgnoreUsers() { - return ignoreUsers; - } - - public void setIgnoreUsers(boolean ignoreUsers) { - this.ignoreUsers = ignoreUsers; - } - - public boolean isIgnoreInputs() { - return ignoreInputs; - } - - public void setIgnoreInputs(boolean ignoreInputs) { - this.ignoreInputs = ignoreInputs; - } - - public boolean isIgnoreCapabiltyProperties() { - return ignoreCapabiltyProperties; - } - - public void setIgnoreCapabiltyProperties(boolean ignoreCapabiltyProperties) { - this.ignoreCapabiltyProperties = ignoreCapabiltyProperties; - } - - public boolean isIgnoreForwardingPath() { - return ignoreServicePath; - } - - public void setIgnoreForwardingPath(boolean ignoreServicePath) { - this.ignoreServicePath = ignoreServicePath; - } - - public boolean isIgnorePolicies() { - return ignorePolicies; - } - - public void setIgnorePolicies(boolean ignorePolicies) { - this.ignorePolicies = ignorePolicies; - } - - public boolean isIgnoreNodeFilter() { - return ignoreNodeFilter; - } - - public void setIgnoreNodeFilter(boolean ignoreNodeFilter) { - this.ignoreNodeFilter = ignoreNodeFilter; - } - - public boolean isIgnoreSubstitutionFilter() { - return ignoreSubstitutionFilter; - } - - public void setIgnoreSubstitutionFilter(boolean ignoreSubstitutionFilter) { - this.ignoreSubstitutionFilter = ignoreSubstitutionFilter; - } - - public boolean isIgnoreDataType() { - return ignoreDataType; - } - - public void setIgnoreDataType(boolean ignoreDataType) { - this.ignoreDataType = ignoreDataType; - } - public JsonParseFlagEnum detectParseFlag() { JsonParseFlagEnum parseFlag; if (isIgnoreComponentInstances()) { @@ -499,4 +318,5 @@ public class ComponentParametersView { } return parseFlag; } + } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeInputCommon.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeInputCommon.java deleted file mode 100644 index fa8c162485..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeInputCommon.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2020, Nordix Foundation. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.model; - -import java.util.List; -import org.openecomp.sdc.be.datatypes.elements.PropertyRule; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; - -public interface IAttributeInputCommon { - - String getType(); - ToscaDataDefinition getSchema(); - List getRules(); - String getName(); -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeOutputCommon.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeOutputCommon.java new file mode 100644 index 0000000000..b2241ca905 --- /dev/null +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/IAttributeOutputCommon.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020, Nordix Foundation. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.model; + +import java.util.List; +import org.openecomp.sdc.be.datatypes.elements.PropertyRule; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; + +public interface IAttributeOutputCommon { + + String getType(); + ToscaDataDefinition getSchema(); + List getRules(); + String getName(); +} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/OutputDefinition.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/OutputDefinition.java index fc8cd0f590..cbff8fa3af 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/OutputDefinition.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/OutputDefinition.java @@ -19,15 +19,15 @@ package org.openecomp.sdc.be.model; -import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; -public class OutputDefinition extends PropertyDefinition { +public class OutputDefinition extends AttributeDefinition { - public OutputDefinition(final PropertyDataDefinition propertyDataDefinition) { + public OutputDefinition(final AttributeDataDefinition propertyDataDefinition) { super(propertyDataDefinition); } - public OutputDefinition(PropertyDefinition propertyDefinition) { + public OutputDefinition(AttributeDefinition propertyDefinition) { super(propertyDefinition); } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java index 6f120dc4ca..0e4753c3f7 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/Resource.java @@ -31,7 +31,6 @@ import lombok.ToString; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.utils.MapUtil; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; @@ -55,8 +54,6 @@ public class Resource extends Component { private Map derivedFromMapOfIdToName; - private List attributes; - private String toscaVersion; public Resource() { @@ -68,24 +65,24 @@ public class Resource extends Component { super(componentMetadataDefinition); if (this.getComponentMetadataDefinition().getMetadataDataDefinition() == null) { this.getComponentMetadataDefinition().componentMetadataDataDefinition = - new ResourceMetadataDataDefinition(); + new ResourceMetadataDataDefinition(); } this.getComponentMetadataDefinition().getMetadataDataDefinition().setComponentType(ComponentTypeEnum.RESOURCE); } public Boolean isAbstract() { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .isAbstract(); + .isAbstract(); } public void setAbstract(Boolean isAbstract) { ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .setAbstract(isAbstract); + .setAbstract(isAbstract); } public String getCost() { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .getCost(); + .getCost(); } public void setCost(String cost) { @@ -94,62 +91,62 @@ public class Resource extends Component { public String getLicenseType() { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .getLicenseType(); + .getLicenseType(); } public void setLicenseType(String licenseType) { ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .setLicenseType(licenseType); + .setLicenseType(licenseType); } public String getToscaResourceName() { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .getToscaResourceName(); + .getToscaResourceName(); } public void setToscaResourceName(String toscaResourceName) { ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .setToscaResourceName(toscaResourceName); + .setToscaResourceName(toscaResourceName); } public ResourceTypeEnum getResourceType() { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .getResourceType(); + .getResourceType(); } public void setResourceType(ResourceTypeEnum resourceType) { ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .setResourceType(resourceType); + .setResourceType(resourceType); } public String getVendorName() { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .getVendorName(); + .getVendorName(); } public void setVendorName(String vendorName) { ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .setVendorName(vendorName); + .setVendorName(vendorName); } public String getVendorRelease() { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .getVendorRelease(); + .getVendorRelease(); } public void setVendorRelease(String vendorRelease) { ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .setVendorRelease(vendorRelease); + .setVendorRelease(vendorRelease); } public String getResourceVendorModelNumber() { return ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .getResourceVendorModelNumber(); + .getResourceVendorModelNumber(); } public void setResourceVendorModelNumber(String resourceVendorModelNumber) { ((ResourceMetadataDataDefinition) getComponentMetadataDefinition().getMetadataDataDefinition()) - .setResourceVendorModelNumber(resourceVendorModelNumber); + .setResourceVendorModelNumber(resourceVendorModelNumber); } @Override @@ -161,22 +158,22 @@ public class Resource extends Component { String result = super.fetchGenericTypeToscaNameFromConfig(); if (null == result) { result = ConfigurationManager.getConfigurationManager().getConfiguration().getGenericAssetNodeTypes() - .get(ResourceTypeEnum.VFC.getValue()); + .get(ResourceTypeEnum.VFC.getValue()); } return result; } private Optional fetchToscaNameFromConfigBasedOnCategory() { return getHeadOption(this.getCategories()).flatMap(category -> getHeadOption(category.getSubcategories()).map( - subCategory -> fetchToscaNameFromConfigBasedOnCategory(category.getName(), subCategory.getName()))); + subCategory -> fetchToscaNameFromConfigBasedOnCategory(category.getName(), subCategory.getName()))); } private String fetchToscaNameFromConfigBasedOnCategory(final String resourceCategory, - final String resourceSubCategory) { + final String resourceSubCategory) { return Optional - .ofNullable(ConfigurationManager.getConfigurationManager().getConfiguration().getResourceNodeTypes()) - .map(categoryNames -> categoryNames.get(resourceCategory)) - .map(subCategoryNames -> subCategoryNames.get(resourceSubCategory)).orElse(null); + .ofNullable(ConfigurationManager.getConfigurationManager().getConfiguration().getResourceNodeTypes()) + .map(categoryNames -> categoryNames.get(resourceCategory)) + .map(subCategoryNames -> subCategoryNames.get(resourceSubCategory)).orElse(null); } @Override @@ -192,16 +189,16 @@ public class Resource extends Component { @Override public boolean deriveFromGeneric() { return this.shouldGenerateInputs() - || (derivedFrom != null && derivedFrom.contains(fetchGenericTypeToscaNameFromConfig())); + || (derivedFrom != null && derivedFrom.contains(fetchGenericTypeToscaNameFromConfig())); } public Map> groupRelationsFromCsarByInstanceName(Resource resource) { List componentInstanceRelationsFromCsar = resource.getComponentInstancesRelations() - .stream().filter(r -> !r.isOriginUI()).collect(Collectors.toList()); + .stream().filter(r -> !r.isOriginUI()).collect(Collectors.toList()); Map> relationsByInstanceId = - MapUtil.groupListBy(componentInstanceRelationsFromCsar, RequirementCapabilityRelDef::getFromNode); + MapUtil.groupListBy(componentInstanceRelationsFromCsar, RequirementCapabilityRelDef::getFromNode); return MapUtil.convertMapKeys(relationsByInstanceId, - instId -> getInstanceInvariantNameFromInstanceId(resource, instId)); + instId -> getInstanceInvariantNameFromInstanceId(resource, instId)); } private String getInstanceInvariantNameFromInstanceId(Resource resource, String instId) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java index a1b07bc58d..2153e22c1d 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/NodeType.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Map; import lombok.Getter; import lombok.Setter; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; @Getter @@ -38,6 +37,5 @@ public class NodeType extends ToscaElement { private List derivedFrom; private List derivedList; private Map derivedFromMapOfIdToName; - private Map attributes; private Map interfaceArtifacts; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java index baea051538..78d4763245 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/datamodel/ToscaElement.java @@ -28,6 +28,7 @@ import lombok.Getter; import lombok.Setter; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; @@ -54,6 +55,7 @@ public abstract class ToscaElement { private Map deploymentArtifacts; private Map additionalInformation; private Map properties; + private Map attributes; private Map capabilities; private Map capabilitiesProperties; private Map requirements; @@ -67,7 +69,7 @@ public abstract class ToscaElement { private Map allVersions; private String toscaVersion; - public ToscaElement(ToscaElementTypeEnum toscaType){ + protected ToscaElement(ToscaElementTypeEnum toscaType){ this.toscaType = toscaType; } @@ -207,7 +209,7 @@ public abstract class ToscaElement { public Long getArchiveTime() { Object archiveTime = getMetadataValue(JsonPresentationFields.ARCHIVE_TIME); if (archiveTime instanceof Integer){ - return new Long((Integer)getMetadataValue(JsonPresentationFields.ARCHIVE_TIME)); + return Long.valueOf((Integer)getMetadataValue(JsonPresentationFields.ARCHIVE_TIME)); } return (Long)archiveTime; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java index 80570e0869..a67f92fff2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/NodeTypeOperation.java @@ -210,7 +210,7 @@ public class NodeTypeOperation extends ToscaElementOperation { } } - if (!componentParametersView.isIgnoreAttributesFrom()) { + if (!componentParametersView.isIgnoreAttributes()) { status = setResourceAttributesFromGraph(componentV, toscaElement); if (status != JanusGraphOperationStatus.OK) { return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java index 92e10a955f..ed9196098e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/TopologyTemplateOperation.java @@ -25,7 +25,6 @@ import fj.data.Either; import java.lang.reflect.Type; import java.util.*; import java.util.Map.Entry; -import java.util.function.BiFunction; import java.util.stream.Collectors; import org.apache.commons.collections.MapUtils; import org.apache.tinkerpop.gremlin.structure.Direction; @@ -51,11 +50,9 @@ import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty; import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition; import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; @@ -661,6 +658,12 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); } } + if (!componentParametersView.isIgnoreComponentInstancesAttributes()) { + status = setComponentInstancesAttributesFromGraph(componentV, toscaElement); + if (status != JanusGraphOperationStatus.OK) { + return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); + } + } if (!componentParametersView.isIgnoreCapabilities()) { status = setCapabilitiesFromGraph(componentV, toscaElement); if (status != JanusGraphOperationStatus.OK) { @@ -742,7 +745,7 @@ public class TopologyTemplateOperation extends ToscaElementOperation { } } - if (!componentParametersView.isIgnoreForwardingPath()) { + if (!componentParametersView.isIgnoreServicePath()) { status = setForwardingGraphPropertiesFromGraph(componentV, toscaElement); if (status != JanusGraphOperationStatus.OK) { return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)); @@ -959,6 +962,18 @@ public class TopologyTemplateOperation extends ToscaElementOperation { return JanusGraphOperationStatus.OK; } + private JanusGraphOperationStatus setComponentInstancesAttributesFromGraph(final GraphVertex componentV, + final TopologyTemplate topologyTemplate) { + final Either, JanusGraphOperationStatus> result = + getDataFromGraph(componentV, EdgeLabelEnum.INST_ATTRIBUTES); + if (result.isLeft()) { + topologyTemplate.setInstAttributes(result.left().value()); + } else if (result.right().value() != JanusGraphOperationStatus.NOT_FOUND) { + return result.right().value(); + } + return JanusGraphOperationStatus.OK; + } + private JanusGraphOperationStatus setComponentInstancesInputsFromGraph(GraphVertex componentV, TopologyTemplate topologyTemplate) { Either, JanusGraphOperationStatus> result = getDataFromGraph(componentV, EdgeLabelEnum.INST_INPUTS); if (result.isLeft()) { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java index 637c91324e..5dbce38ee2 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaElementOperation.java @@ -921,7 +921,7 @@ public abstract class ToscaElementOperation extends BaseOperation { switch (label) { case NODE_TYPE: toscaElement = new NodeType(); - ((NodeType) toscaElement).setAttributes(getAttributesFromComponentV(componentV)); + toscaElement.setAttributes(getAttributesFromComponentV(componentV)); break; case TOPOLOGY_TEMPLATE: toscaElement = new TopologyTemplate(); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java index 532a641e2f..b16e129d2e 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/operations/ToscaOperationFacade.java @@ -56,7 +56,6 @@ import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; 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.ComponentInstanceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.DataTypeDataDefinition; @@ -79,6 +78,7 @@ import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.PromoteVersionEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; 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.CatalogUpdateTimestamp; import org.openecomp.sdc.be.model.Component; @@ -155,7 +155,7 @@ public class ToscaOperationFacade { public Either getToscaFullElement(String componentId) { ComponentParametersView filters = new ComponentParametersView(); filters.setIgnoreCapabiltyProperties(false); - filters.setIgnoreForwardingPath(false); + filters.setIgnoreServicePath(false); return getToscaElement(componentId, filters); } @@ -286,7 +286,8 @@ public class ToscaOperationFacade { // region - ToscaElement Delete public StorageOperationStatus markComponentToDelete(Component componentToDelete) { - if ((componentToDelete.getIsDeleted() != null) && componentToDelete.getIsDeleted() && !componentToDelete.isHighestVersion()) { + if (Boolean.TRUE.equals(componentToDelete.getIsDeleted()) + && Boolean.FALSE.equals(componentToDelete.isHighestVersion())) { // component already marked for delete return StorageOperationStatus.OK; } else { @@ -294,7 +295,8 @@ public class ToscaOperationFacade { Either getResponse = janusGraphDao .getVertexById(componentToDelete.getUniqueId(), JsonParseFlagEnum.ParseAll); if (getResponse.isRight()) { - log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), getResponse.right().value()); + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentToDelete.getUniqueId(), + getResponse.right().value()); return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getResponse.right().value()); } @@ -360,7 +362,7 @@ public class ToscaOperationFacade { public Either getFullLatestComponentByToscaResourceName(String toscaResourceName) { ComponentParametersView fetchAllFilter = new ComponentParametersView(); - fetchAllFilter.setIgnoreForwardingPath(true); + fetchAllFilter.setIgnoreServicePath(true); fetchAllFilter.setIgnoreCapabiltyProperties(false); return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter); } @@ -1203,10 +1205,11 @@ public class ToscaOperationFacade { Either getVertexEither = janusGraphDao .getVertexById(componentId, JsonParseFlagEnum.NoParse); if (getVertexEither.isRight()) { - log.debug("Couldn't fetch component with and unique id {}, error: {}", componentId, getVertexEither.right().value()); - return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); + log.debug(COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR, componentId, getVertexEither.right().value()); + return Either + .right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getVertexEither.right().value())); - } + } Either toscaElement = topologyTemplateOperation.getToscaElement(componentId); @@ -1626,7 +1629,7 @@ public class ToscaOperationFacade { } - public StorageOperationStatus associateInstAttributeToComponentToInstances(Map> instArttributes, Component component) { + public StorageOperationStatus associateInstAttributeToComponentToInstances(Map> instArttributes, Component component) { Either getVertexEither = janusGraphDao.getVertexById(component.getUniqueId(), JsonParseFlagEnum.NoParse); if (getVertexEither.isRight()) { @@ -1640,11 +1643,11 @@ public class ToscaOperationFacade { if (instArttributes != null) { MapAttributesDataDefinition attributesMap; - for (Entry> entry : instArttributes.entrySet()) { - final List value = entry.getValue(); + for (Entry> entry : instArttributes.entrySet()) { + final List value = entry.getValue(); attributesMap = new MapAttributesDataDefinition(); - attributesMap.setMapToscaDataDefinition(value.stream().map(AttributeDataDefinition::new) - .collect(Collectors.toMap(AttributeDataDefinition::getName, e -> e))); + attributesMap.setMapToscaDataDefinition(value.stream().map(AttributeDefinition::new) + .collect(Collectors.toMap(AttributeDefinition::getName, e -> e))); instAttr.put(entry.getKey(), attributesMap); } } @@ -2081,7 +2084,7 @@ public class ToscaOperationFacade { if (latestComponents.size() > 1) { for (Component component : latestComponents) { - if (component.isHighestVersion()) { + if (Boolean.TRUE.equals(component.isHighestVersion())) { LinkedList highestComponent = new LinkedList<>(); highestComponent.add(component); return Either.left(highestComponent); @@ -2235,7 +2238,7 @@ public class ToscaOperationFacade { // correct audit records!!!!! return Either.right(StorageOperationStatus.NOT_FOUND); } - return getToscaElement((String) resourceMetadataData.getUniqueId()); + return getToscaElement(resourceMetadataData.getUniqueId()); } } else { resourceMetadataDataList = byCsar.left().value(); @@ -2551,17 +2554,19 @@ public class ToscaOperationFacade { Either result = null; StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, newPropertyDefinition, JsonPresentationFields.NAME); if (status != StorageOperationStatus.OK) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to add the property {} to the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getName(), status); - result = Either.right(status); - } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, + newPropertyDefinition.getName(), component.getName(), status); + result = Either.right(status); + } if (result == null) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreProperties(false); getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); if (getUpdatedComponentRes.isRight()) { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to get updated resource {}. Status is {}. ", component.getUniqueId(), getUpdatedComponentRes.right().value()); - result = Either.right(status); - } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, + component.getUniqueId(), getUpdatedComponentRes.right().value()); + result = Either.right(status); + } } if (result == null) { Optional newProperty = (getUpdatedComponentRes.left().value()) @@ -2569,17 +2574,19 @@ public class ToscaOperationFacade { if (newProperty.isPresent()) { result = Either.left(newProperty.get()); } else { - CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find recently added property {} on the resource {}. Status is {}. ", newPropertyDefinition.getName(), component.getUniqueId(), StorageOperationStatus.NOT_FOUND); - result = Either.right(StorageOperationStatus.NOT_FOUND); - } + CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, + FAILED_TO_FIND_RECENTLY_ADDED_PROPERTY_ON_THE_RESOURCE_STATUS_IS, newPropertyDefinition.getName(), + component.getUniqueId(), StorageOperationStatus.NOT_FOUND); + result = Either.right(StorageOperationStatus.NOT_FOUND); + } } return result; } - public Either addAttributeOfResource(Component component, AttributeDataDefinition newAttributeDef) { + public Either addAttributeOfResource(Component component, AttributeDefinition newAttributeDef) { Either getUpdatedComponentRes = null; - Either result = null; + Either result = null; if (newAttributeDef.getUniqueId() == null || newAttributeDef.getUniqueId().isEmpty()) { String attUniqueId = UniqueIdBuilder.buildAttributeUid(component.getUniqueId(), newAttributeDef.getName()); newAttributeDef.setUniqueId(attUniqueId); @@ -2593,7 +2600,7 @@ public class ToscaOperationFacade { } if (result == null) { ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreAttributesFrom(false); + filter.setIgnoreAttributes(false); getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); if (getUpdatedComponentRes.isRight()) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); @@ -2601,7 +2608,7 @@ public class ToscaOperationFacade { } } if (result == null) { - Optional newAttribute = ((Resource) getUpdatedComponentRes.left().value()) + Optional newAttribute = ((Resource) getUpdatedComponentRes.left().value()) .getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); if (newAttribute.isPresent()) { result = Either.left(newAttribute.get()); @@ -2613,10 +2620,10 @@ public class ToscaOperationFacade { return result; } - public Either updateAttributeOfResource(Component component, AttributeDataDefinition newAttributeDef) { + public Either updateAttributeOfResource(Component component, AttributeDefinition newAttributeDef) { Either getUpdatedComponentRes = null; - Either result = null; + Either result = null; StorageOperationStatus status = getToscaElementOperation(component).updateToscaDataOfToscaElement(component.getUniqueId(), EdgeLabelEnum.ATTRIBUTES, VertexTypeEnum.ATTRIBUTES, newAttributeDef, JsonPresentationFields.NAME); if (status != StorageOperationStatus.OK) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS, newAttributeDef.getName(), component.getName(), status); @@ -2624,7 +2631,7 @@ public class ToscaOperationFacade { } if (result == null) { ComponentParametersView filter = new ComponentParametersView(true); - filter.setIgnoreAttributesFrom(false); + filter.setIgnoreAttributes(false); getUpdatedComponentRes = getToscaElement(component.getUniqueId(), filter); if (getUpdatedComponentRes.isRight()) { CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS, component.getUniqueId(), getUpdatedComponentRes.right().value()); @@ -2632,7 +2639,7 @@ public class ToscaOperationFacade { } } if (result == null) { - Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()) + Optional newProperty = ((Resource) getUpdatedComponentRes.left().value()) .getAttributes().stream().filter(p -> p.getName().equals(newAttributeDef.getName())).findAny(); if (newProperty.isPresent()) { result = Either.left(newProperty.get()); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java index 2c51ff472c..db6a8e100f 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsonjanusgraph/utils/ModelConverter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -40,7 +40,6 @@ import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; -import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; @@ -128,6 +127,10 @@ import org.openecomp.sdc.be.ui.model.PropertyAssignmentUi; import org.openecomp.sdc.common.log.wrappers.Logger; public class ModelConverter { + + private ModelConverter() { + } + public static final String CAP_PROP_DELIM = "#"; private static final Logger log = Logger.getLogger(ModelConverter.class); @@ -142,13 +145,13 @@ public class ModelConverter { @SuppressWarnings("unchecked") public static T convertFromToscaElement(ToscaElement toscaElement) { switch (toscaElement.getComponentType()) { - case RESOURCE: - return (T) convertToResource(toscaElement); - case SERVICE: - case PRODUCT: - return (T) convertToService(toscaElement); - default: - return null; + case RESOURCE: + return (T) convertToResource(toscaElement); + case SERVICE: + case PRODUCT: + return (T) convertToService(toscaElement); + default: + return null; } } @@ -189,9 +192,9 @@ public class ModelConverter { } } - private static Service convertToService(ToscaElement toscaElement) { - Service service = new Service(); - convertComponentFields(service, toscaElement); + private static Service convertToService(ToscaElement toscaElement) { + Service service = new Service(); + convertComponentFields(service, toscaElement); convertServiceSpecificFields(toscaElement, service); @@ -199,19 +202,17 @@ public class ModelConverter { convertComponentInstances(topologyTemplate, service); - convertInputs(topologyTemplate, service); + convertInputs(topologyTemplate, service); - convertProperties(topologyTemplate, service); + convertProperties(topologyTemplate, service); - convertPolicies(topologyTemplate, service); - - convertProperties(topologyTemplate, service); + convertPolicies(topologyTemplate, service); - convertPolicies(topologyTemplate, service); + convertAttributesToComponent(topologyTemplate, service); convertGroups(topologyTemplate, service); - setCapabilitiesToComponentAndGroups(topologyTemplate, service); + setCapabilitiesToComponentAndGroups(topologyTemplate, service); convertPolicies(topologyTemplate, service); @@ -236,18 +237,18 @@ public class ModelConverter { return service; } - private static void convertServiceSpecificFields(ToscaElement toscaElement, Service service) { - service.setProjectCode((String) toscaElement.getMetadataValue(JsonPresentationFields.PROJECT_CODE)); - service.setDistributionStatus(DistributionStatusEnum - .findState((String) toscaElement.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS))); - service.setEcompGeneratedNaming( - (Boolean) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.ECOMP_GENERATED_NAMING, true)); - service.setNamingPolicy((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.NAMING_POLICY, - StringUtils.EMPTY)); - service.setEnvironmentContext( - (String) toscaElement.getMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT)); - service.setInstantiationType((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.INSTANTIATION_TYPE, StringUtils.EMPTY)); - } + private static void convertServiceSpecificFields(ToscaElement toscaElement, Service service) { + service.setProjectCode((String) toscaElement.getMetadataValue(JsonPresentationFields.PROJECT_CODE)); + service.setDistributionStatus(DistributionStatusEnum + .findState((String) toscaElement.getMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS))); + service.setEcompGeneratedNaming( + (Boolean) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.ECOMP_GENERATED_NAMING, true)); + service.setNamingPolicy((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.NAMING_POLICY, + StringUtils.EMPTY)); + service.setEnvironmentContext( + (String) toscaElement.getMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT)); + service.setInstantiationType((String) toscaElement.getMetadataValueOrDefault(JsonPresentationFields.INSTANTIATION_TYPE, StringUtils.EMPTY)); + } private static Resource convertToResource(ToscaElement toscaElement) { Resource resource = new Resource(); @@ -264,29 +265,30 @@ public class ModelConverter { if (toscaVersion != null) { resource.setToscaVersion(toscaVersion); } - convertAttributes(nodeType, resource); + convertAttributesToResource(nodeType, resource); convertCapabilities(nodeType, resource); convertRequirements(nodeType, resource); convertInterfaces(nodeType, resource); convertDataTypes(nodeType, resource); - } else { - TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; - if (resource.getResourceType() == ResourceTypeEnum.VF || resource.getResourceType() == ResourceTypeEnum.PNF) { - resource.setCsarUUID((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); - resource.setCsarVersion((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_VERSION)); - resource.setImportedToscaChecksum((String) topologyTemplate.getMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM)); + } else { + TopologyTemplate topologyTemplate = (TopologyTemplate) toscaElement; + if (resource.getResourceType() == ResourceTypeEnum.VF || resource.getResourceType() == ResourceTypeEnum.PNF) { + resource.setCsarUUID((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_UUID)); + resource.setCsarVersion((String) topologyTemplate.getMetadataValue(JsonPresentationFields.CSAR_VERSION)); + resource.setImportedToscaChecksum((String) topologyTemplate.getMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM)); convertInterfaces(topologyTemplate, resource); } convertComponentInstances(topologyTemplate, resource); convertRelations(topologyTemplate, resource); convertInputs(topologyTemplate, resource); convertGroups(topologyTemplate, resource); - setCapabilitiesToComponentAndGroups(topologyTemplate, resource); + setCapabilitiesToComponentAndGroups(topologyTemplate, resource); convertPolicies(topologyTemplate, resource); convertNodeFiltersComponents(topologyTemplate, resource); convertSubstitutionFiltersComponents(topologyTemplate, resource); convertProperties(topologyTemplate, resource); + convertAttributesToComponent(topologyTemplate, resource); setCapabilitiesToComponent(topologyTemplate, resource); setRequirementsToComponent(topologyTemplate, resource); convertDataTypes(topologyTemplate, resource); @@ -295,7 +297,7 @@ public class ModelConverter { convertAdditionalInformation(toscaElement, resource); return resource; - } + } private static void convertInterfaces(TopologyTemplate toscaElement, Resource resource) { Map interfaces = toscaElement.getInterfaces(); @@ -319,25 +321,20 @@ public class ModelConverter { service.setInterfaces(copy); } - private static void convertAttributes(NodeType nodeType, Resource resource) { + private static void convertAttributesToResource(NodeType nodeType, Resource resource) { Map attributes = nodeType.getAttributes(); if (attributes != null) { - final List attrs = attributes.values().stream() - .collect(Collectors.toList()); - resource.setAttributes(attrs); + final Map attributeDefinitionMap = attributes.entrySet().stream() + .collect(Collectors.toMap(Entry::getKey, o -> new AttributeDefinition(o.getValue()))); + resource.setAttributes(new ArrayList<>(attributeDefinitionMap.values())); } } - private static PropertyDefinition fromDataDefinition(String resourceId, PropertyDataDefinition dataDefinition) { - PropertyDefinition attributeDefinition = new PropertyDefinition(dataDefinition); - attributeDefinition.setParentUniqueId(resourceId); - return attributeDefinition; - } - private static void convertInterfaces(NodeType nodeType, Resource resource) { Map interfaceArtifacts = nodeType.getInterfaceArtifacts(); if (interfaceArtifacts != null) { - Map interfaces = interfaceArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new InterfaceDefinition(en.getValue()))); + Map interfaces = interfaceArtifacts.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, en -> new InterfaceDefinition(en.getValue()))); resource.setInterfaces(interfaces); } } @@ -380,14 +377,16 @@ public class ModelConverter { } - public static void setComponentInstancesInformationalArtifactsToComponent(Map instanceArtifacts, Component component) { + public static void setComponentInstancesInformationalArtifactsToComponent(Map instanceArtifacts, + Component component) { List instances = component.getComponentInstances(); if (instanceArtifacts != null && instances != null) { instanceArtifacts.entrySet().forEach(e -> { Optional ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); if (ci.isPresent()) { Map mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); - Map deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); + Map deplArt = mapToscaDataDefinition.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); ci.get().setArtifacts(deplArt); } @@ -395,14 +394,16 @@ public class ModelConverter { } } - public static void setComponentInstancesDeploymentArtifactsToComponent(Map instDeploymentArtifacts, Component component) { + public static void setComponentInstancesDeploymentArtifactsToComponent(Map instDeploymentArtifacts, + Component component) { List instances = component.getComponentInstances(); if (instDeploymentArtifacts != null && instances != null) { instDeploymentArtifacts.entrySet().forEach(e -> { Optional ci = instances.stream().filter(i -> i.getUniqueId().equals(e.getKey())).findFirst(); if (ci.isPresent()) { Map mapToscaDataDefinition = e.getValue().getMapToscaDataDefinition(); - Map deplArt = mapToscaDataDefinition.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); + Map deplArt = mapToscaDataDefinition.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, en -> new ArtifactDefinition(en.getValue()))); ci.get().setDeploymentArtifacts(deplArt); } @@ -543,7 +544,7 @@ public class ModelConverter { private static void convertCapabilities(Component component, TopologyTemplate topologyTemplate) { convertTopologyTemplateCapabilities(component, topologyTemplate); - if(componentInstancesCapabilitiesExist(component) || groupsCapabilitiesExist(component)){ + if (componentInstancesCapabilitiesExist(component) || groupsCapabilitiesExist(component)) { topologyTemplate.setCalculatedCapabilities(new HashMap<>()); topologyTemplate.setCalculatedCapabilitiesProperties(new HashMap<>()); } @@ -552,11 +553,11 @@ public class ModelConverter { } private static void convertGroupsCapabilities(Component component, TopologyTemplate topologyTemplate) { - if(groupsCapabilitiesExist(component)){ + if (groupsCapabilitiesExist(component)) { component.getGroups() - .stream() - .filter(g -> MapUtils.isNotEmpty(g.getCapabilities())) - .forEach(g -> addCapabilities(topologyTemplate, g.getCapabilities(), g.getUniqueId())); + .stream() + .filter(g -> MapUtils.isNotEmpty(g.getCapabilities())) + .forEach(g -> addCapabilities(topologyTemplate, g.getCapabilities(), g.getUniqueId())); } } @@ -566,21 +567,22 @@ public class ModelConverter { Map toscaCapMap = new HashMap<>(); Map toscaCapPropMap = new HashMap<>(); - if (MapUtils.isNotEmpty(capabilities )) { + if (MapUtils.isNotEmpty(capabilities)) { capabilities.forEach((s, caps) -> { - if (CollectionUtils.isNotEmpty(caps)) { - List capList = caps.stream().filter(capabilityDefinition -> capabilityDefinition.getOwnerId() - .equals(component.getUniqueId())).map(CapabilityDataDefinition::new).collect(Collectors.toList()); + if (CollectionUtils.isNotEmpty(caps)) { + List capList = caps.stream().filter(capabilityDefinition -> capabilityDefinition.getOwnerId() + .equals(component.getUniqueId())).map(CapabilityDataDefinition::new).collect(Collectors.toList()); - populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList); - } + populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList); } + } ); toscaElement.setCapabilities(toscaCapMap); toscaElement.setCapabilitiesProperties(toscaCapPropMap); } } + private static void populateCapabilityMap(Map toscaCapMap, Map toscaCapPropMap, String s, List caps, @@ -607,26 +609,27 @@ public class ModelConverter { Map toscaReqMap = new HashMap<>(); - if (MapUtils.isNotEmpty(requirements )) { - requirements.forEach((s, reqs)-> { - if (CollectionUtils.isNotEmpty(reqs)) { - List reqList = reqs.stream().filter(requirementDefinition -> requirementDefinition.getOwnerId() - .equals(component.getUniqueId())).map(RequirementDataDefinition::new).collect(Collectors.toList()); + if (MapUtils.isNotEmpty(requirements)) { + requirements.forEach((s, reqs) -> { + if (CollectionUtils.isNotEmpty(reqs)) { + List reqList = reqs.stream().filter(requirementDefinition -> requirementDefinition.getOwnerId() + .equals(component.getUniqueId())).map(RequirementDataDefinition::new).collect(Collectors.toList()); - ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList); - toscaReqMap.put(s, listRequirementDataDefinition); - } + ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList); + toscaReqMap.put(s, listRequirementDataDefinition); } + } ); toscaElement.setRequirements(toscaReqMap); } } + private static void convertComponentInstancesCapabilities(Component component, TopologyTemplate topologyTemplate) { if (componentInstancesCapabilitiesExist(component)) { component.getComponentInstances() - .stream() - .filter(i -> MapUtils.isNotEmpty(i.getCapabilities())) - .forEach(i -> addCapabilities(topologyTemplate, i.getCapabilities(), i.getUniqueId())); + .stream() + .filter(i -> MapUtils.isNotEmpty(i.getCapabilities())) + .forEach(i -> addCapabilities(topologyTemplate, i.getCapabilities(), i.getUniqueId())); } } @@ -645,104 +648,113 @@ public class ModelConverter { private static boolean componentInstancesCapabilitiesExist(Component component) { return component.getCapabilities() != null && component.getComponentInstances() != null - && component.getComponentInstances() - .stream() - .anyMatch(ci->MapUtils.isNotEmpty(ci.getCapabilities())); + && component.getComponentInstances() + .stream() + .anyMatch(ci -> MapUtils.isNotEmpty(ci.getCapabilities())); } + private static boolean groupsCapabilitiesExist(Component component) { return component.getCapabilities() != null && component.getGroups() != null - && component.getGroups() - .stream() - .anyMatch(g->MapUtils.isNotEmpty(g.getCapabilities())); + && component.getGroups() + .stream() + .anyMatch(g -> MapUtils.isNotEmpty(g.getCapabilities())); } - public static MapCapabilityProperty convertToMapOfMapCapabilityProperties(Map> capabilities, String ownerId, boolean isAtomicType) { + public static MapCapabilityProperty convertToMapOfMapCapabilityProperties(Map> capabilities, String ownerId, + boolean isAtomicType) { Map toscaCapPropMap = new HashMap<>(); - if(MapUtils.isNotEmpty(capabilities)){ - capabilities.forEach((s, caps)-> addCapsProperties(ownerId, isAtomicType, toscaCapPropMap, caps)); + if (MapUtils.isNotEmpty(capabilities)) { + capabilities.forEach((s, caps) -> addCapsProperties(ownerId, isAtomicType, toscaCapPropMap, caps)); } return new MapCapabilityProperty(toscaCapPropMap); } - private static void addCapsProperties(String ownerId, boolean isAtomicType, Map toscaCapPropMap, List caps) { + private static void addCapsProperties(String ownerId, boolean isAtomicType, Map toscaCapPropMap, + List caps) { if (CollectionUtils.isNotEmpty(caps)) { caps.forEach(cap -> addCapProperties(ownerId, isAtomicType, toscaCapPropMap, cap)); } } - private static void addCapProperties(String ownerId, boolean isAtomicType, Map toscaCapPropMap, CapabilityDefinition cap) { + private static void addCapProperties(String ownerId, boolean isAtomicType, Map toscaCapPropMap, + CapabilityDefinition cap) { if (CollectionUtils.isNotEmpty(cap.getProperties())) { MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(cap.getProperties() - .stream() - .map(PropertyDataDefinition::new) - .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p))); - toscaCapPropMap.put(buildCapabilityPropertyKey(isAtomicType, cap.getType(),cap.getName(),ownerId, cap), - new MapPropertiesDataDefinition(dataToCreate)); + .stream() + .map(PropertyDataDefinition::new) + .collect(Collectors.toMap(PropertyDataDefinition::getName, p -> p))); + toscaCapPropMap.put(buildCapabilityPropertyKey(isAtomicType, cap.getType(), cap.getName(), ownerId, cap), + new MapPropertiesDataDefinition(dataToCreate)); } } - public static String buildCapabilityPropertyKey(boolean isAtomicType, String capabilityType, String capabilityName, String componentInstanceUniqueId, CapabilityDefinition cap) { + public static String buildCapabilityPropertyKey(boolean isAtomicType, String capabilityType, String capabilityName, + String componentInstanceUniqueId, CapabilityDefinition cap) { StringBuilder sb = new StringBuilder(componentInstanceUniqueId); sb.append(CAP_PROP_DELIM) - .append(cap.getOwnerId()) - .append(CAP_PROP_DELIM); - if(!isAtomicType && !componentInstanceUniqueId.equals(cap.getOwnerId())){ + .append(cap.getOwnerId()) + .append(CAP_PROP_DELIM); + if (!isAtomicType && !componentInstanceUniqueId.equals(cap.getOwnerId())) { sb.append(cap.getOwnerId()) - .append(CAP_PROP_DELIM); + .append(CAP_PROP_DELIM); } return sb.append(capabilityType) - .append(CAP_PROP_DELIM) - .append(capabilityName).toString(); + .append(CAP_PROP_DELIM) + .append(capabilityName).toString(); } - public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map> instCapabilities, String ownerId) { + public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map> instCapabilities, + String ownerId) { return convertToMapOfMapCapabiltyProperties(instCapabilities, ownerId, false); } - public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map> capabilities, String ownerId, boolean fromCsar) { + public static MapCapabilityProperty convertToMapOfMapCapabiltyProperties(Map> capabilities, String ownerId, + boolean fromCsar) { Map toscaCapPropMap = new HashMap<>(); - if(MapUtils.isNotEmpty(capabilities)) - capabilities.forEach((s, caps)-> { - - if (caps != null && !caps.isEmpty()) { - - MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); - - for (CapabilityDefinition cap : caps) { - List capPrps = cap.getProperties(); - if (capPrps != null) { - - for (ComponentInstanceProperty cip : capPrps) { - dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); - } - // format key of capability properties : - // VF instance in service : instanceId#ownerId#type#capName - // VFC instance ion VF : instanceId#ownerId#type#capName -> instanceId=ownerId - - StringBuilder sb = new StringBuilder(ownerId); - sb.append(CAP_PROP_DELIM); - if (fromCsar) { - sb.append(ownerId); - } else { - sb.append(cap.getOwnerId()); - } - sb.append(CAP_PROP_DELIM).append(s).append(CAP_PROP_DELIM).append(cap.getName()); - toscaCapPropMap.put(sb.toString(), new MapPropertiesDataDefinition(dataToCreate)); - } - } - } - } - ); + if (MapUtils.isNotEmpty(capabilities)) { + capabilities.forEach((s, caps) -> { + + if (caps != null && !caps.isEmpty()) { + + MapPropertiesDataDefinition dataToCreate = new MapPropertiesDataDefinition(); + + for (CapabilityDefinition cap : caps) { + List capPrps = cap.getProperties(); + if (capPrps != null) { + + for (ComponentInstanceProperty cip : capPrps) { + dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip)); + } + // format key of capability properties : + // VF instance in service : instanceId#ownerId#type#capName + // VFC instance ion VF : instanceId#ownerId#type#capName -> instanceId=ownerId + + StringBuilder sb = new StringBuilder(ownerId); + sb.append(CAP_PROP_DELIM); + if (fromCsar) { + sb.append(ownerId); + } else { + sb.append(cap.getOwnerId()); + } + sb.append(CAP_PROP_DELIM).append(s).append(CAP_PROP_DELIM).append(cap.getName()); + toscaCapPropMap.put(sb.toString(), new MapPropertiesDataDefinition(dataToCreate)); + } + } + } + } + ); + } return new MapCapabilityProperty(toscaCapPropMap); } - private static MapListCapabilityDataDefinition convertToMapListCapabiltyDataDefinition(Map> instCapabilities) { + private static MapListCapabilityDataDefinition convertToMapListCapabiltyDataDefinition(Map> instCapabilities) { Map mapToscaDataDefinition = new HashMap<>(); for (Entry> instCapability : instCapabilities.entrySet()) { - mapToscaDataDefinition.put(instCapability.getKey(), new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))); + mapToscaDataDefinition.put(instCapability.getKey(), + new ListCapabilityDataDefinition(instCapability.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))); } return new MapListCapabilityDataDefinition(mapToscaDataDefinition); @@ -759,17 +771,20 @@ public class ModelConverter { if (topologyTemplate.getCalculatedRequirements() == null) { topologyTemplate.setCalculatedRequirements(new HashMap<>()); } - topologyTemplate.getCalculatedRequirements().put(instance.getUniqueId(), convertToMapListRequirementDataDefinition(instRequirements)); + topologyTemplate.getCalculatedRequirements() + .put(instance.getUniqueId(), convertToMapListRequirementDataDefinition(instRequirements)); } } } } - private static MapListRequirementDataDefinition convertToMapListRequirementDataDefinition(Map> instRequirements) { + private static MapListRequirementDataDefinition convertToMapListRequirementDataDefinition( + Map> instRequirements) { Map mapToscaDataDefinition = new HashMap<>(); for (Entry> instRequirement : instRequirements.entrySet()) { - mapToscaDataDefinition.put(instRequirement.getKey(), new ListRequirementDataDefinition(instRequirement.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))); + mapToscaDataDefinition.put(instRequirement.getKey(), new ListRequirementDataDefinition( + instRequirement.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))); } return new MapListRequirementDataDefinition(mapToscaDataDefinition); @@ -797,17 +812,15 @@ public class ModelConverter { component.setDerivedFromGenericType(toscaElement.getDerivedFromGenericType()); component.setDerivedFromGenericVersion(toscaElement.getDerivedFromGenericVersion()); - Map properties = toscaElement.getProperties(); - if(MapUtils.isNotEmpty(properties)) { - List propertiesMap = properties.values().stream().map(x -> new PropertyDefinition(x)).collect(Collectors.toList()); - component.setProperties(propertiesMap); - } - - //archive - component.setArchived(toscaElement.isArchived() == null ? false : toscaElement.isArchived()); + Map properties = toscaElement.getProperties(); + if (MapUtils.isNotEmpty(properties)) { + List propertiesMap = properties.values().stream().map(x -> new PropertyDefinition(x)).collect(Collectors.toList()); + component.setProperties(propertiesMap); + } + //archive + component.setArchived(toscaElement.isArchived() == null ? false : toscaElement.isArchived()); - //component.setArchiveTime(toscaElement.getArchiveTime() == null ? 0L : toscaElement.getArchiveTime()); component.setArchiveTime(toscaElement.getArchiveTime()); component.setVspArchived(toscaElement.isVspArchived() == null ? false : toscaElement.isVspArchived()); @@ -818,25 +831,25 @@ public class ModelConverter { resource.setVendorName((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_NAME)); resource.setVendorRelease((String) toscaElement.getMetadataValue(JsonPresentationFields.VENDOR_RELEASE)); // field isn't mandatory , but shouldn't be null(should be an empty string instead) - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null){ + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)) != null) { resource.setResourceVendorModelNumber((String) toscaElement.getMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER)); } else { resource.setResourceVendorModelNumber(""); } - + } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { Service service = (Service) component; - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null){ + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)) != null) { service.setServiceType((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_TYPE)); } else { service.setServiceType(""); } - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null){ + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)) != null) { service.setServiceRole((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_ROLE)); } else { service.setServiceRole(""); } - if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_FUNCTION)) != null){ + if (((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_FUNCTION)) != null) { service.setServiceFunction((String) toscaElement.getMetadataValue(JsonPresentationFields.SERVICE_FUNCTION)); } else { service.setServiceFunction(""); @@ -854,36 +867,36 @@ public class ModelConverter { final List metadataKeys = getCategorySpecificMetadataKeys(toscaElement); if (CollectionUtils.isNotEmpty(metadataKeys)) { final Map categorySpecificMetadata = new HashMap<>(); - for (final String metadataKey: metadataKeys) { + for (final String metadataKey : metadataKeys) { categorySpecificMetadata.put(metadataKey, (String) toscaElement.getMetadata().get(metadataKey)); } - component.setCategorySpecificMetadata(categorySpecificMetadata ); + component.setCategorySpecificMetadata(categorySpecificMetadata); } } - - private static List getCategorySpecificMetadataKeys(final ToscaElement toscaElement){ + + private static List getCategorySpecificMetadataKeys(final ToscaElement toscaElement) { final List metadataKeys = new ArrayList<>(); final Optional category = getCategory(toscaElement); if (category.isPresent()) { if (CollectionUtils.isNotEmpty(category.get().getMetadataKeys())) { - for (final MetadataKeyDataDefinition metadataKey: category.get().getMetadataKeys()) { + for (final MetadataKeyDataDefinition metadataKey : category.get().getMetadataKeys()) { metadataKeys.add(metadataKey.getName()); } } final Optional subCategory = getSubCategory(category.get()); if (subCategory.isPresent() && CollectionUtils.isNotEmpty(subCategory.get().getMetadataKeys())) { - for (final MetadataKeyDataDefinition metadataKey: subCategory.get().getMetadataKeys()) { + for (final MetadataKeyDataDefinition metadataKey : subCategory.get().getMetadataKeys()) { metadataKeys.add(metadataKey.getName()); } } } return metadataKeys; } - + private static Optional getCategory(ToscaElement toscaElement) { return CollectionUtils.isEmpty(toscaElement.getCategories()) ? Optional.empty() : Optional.of(toscaElement.getCategories().get(0)); } - + private static Optional getSubCategory(CategoryDefinition category) { return CollectionUtils.isEmpty(category.getSubcategories()) ? Optional.empty() : Optional.of(category.getSubcategories().get(0)); } @@ -908,7 +921,7 @@ public class ModelConverter { convertArtifacts(resource, nodeType); convertCapabilities(resource, nodeType); convertRequirements(resource, nodeType); - convertAttributes(resource, nodeType); + convertAttributesToNodeType(resource, nodeType); convertProperties(resource, nodeType); convertInterfaces(resource, nodeType); return nodeType; @@ -917,7 +930,8 @@ public class ModelConverter { private static void convertProperties(Resource resource, NodeType nodeType) { List properties = resource.getProperties(); if (properties != null && !properties.isEmpty()) { - Map propertiesMap = properties.stream().collect(Collectors.toMap(PropertyDefinition::getName, PropertyDataDefinition::new)); + Map propertiesMap = properties.stream() + .collect(Collectors.toMap(PropertyDefinition::getName, PropertyDataDefinition::new)); nodeType.setProperties(propertiesMap); } } @@ -925,7 +939,8 @@ public class ModelConverter { private static void convertInterfaces(Resource resource, NodeType nodeType) { Map interfaces = resource.getInterfaces(); if (interfaces != null) { - Map interfaceArtifacts = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, x -> new InterfaceDataDefinition(x.getValue()))); + Map interfaceArtifacts = interfaces.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, x -> new InterfaceDataDefinition(x.getValue()))); nodeType.setInterfaceArtifacts(interfaceArtifacts); } } @@ -933,7 +948,8 @@ public class ModelConverter { private static void convertAdditionalInformation(Component component, ToscaElement toscaElement) { List additionalInformation = component.getAdditionalInformation(); if (additionalInformation != null) { - Map addInfo = additionalInformation.stream().collect(Collectors.toMap(AdditionalInformationDefinition::getUniqueId, AdditionalInfoParameterDataDefinition::new)); + Map addInfo = additionalInformation.stream() + .collect(Collectors.toMap(AdditionalInformationDefinition::getUniqueId, AdditionalInfoParameterDataDefinition::new)); toscaElement.setAdditionalInformation(addInfo); } } @@ -941,7 +957,8 @@ public class ModelConverter { private static void convertAdditionalInformation(ToscaElement toscaElement, Component resource) { Map additionalInformation = toscaElement.getAdditionalInformation(); if (additionalInformation != null) { - List addInfo = additionalInformation.values().stream().map(AdditionalInformationDefinition::new).collect(Collectors.toList()); + List addInfo = additionalInformation.values().stream().map(AdditionalInformationDefinition::new) + .collect(Collectors.toList()); resource.setAdditionalInformation(addInfo); } } @@ -1009,6 +1026,7 @@ public class ModelConverter { } service.setServiceApiArtifacts(copy); } + private static void convertServicePaths(TopologyTemplate topologyTemplate, Service service) { Map servicePaths = topologyTemplate.getForwardingPaths(); Map copy; @@ -1024,19 +1042,22 @@ public class ModelConverter { private static void convertArtifacts(Component component, ToscaElement toscaElement) { Map artifacts = component.getArtifacts(); if (artifacts != null) { - Map copy = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + Map copy = artifacts.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); toscaElement.setArtifacts(copy); } Map toscaArtifacts = component.getToscaArtifacts(); if (toscaArtifacts != null) { - Map copy = toscaArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + Map copy = toscaArtifacts.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); toscaElement.setToscaArtifacts(copy); } Map deploymentArtifacts = component.getDeploymentArtifacts(); if (deploymentArtifacts != null) { - Map copy = deploymentArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + Map copy = deploymentArtifacts.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); toscaElement.setDeploymentArtifacts(copy); } } @@ -1044,7 +1065,8 @@ public class ModelConverter { private static void convertServiceApiArtifacts(Service service, TopologyTemplate topologyTemplate) { Map serviceApiArtifacts = service.getServiceApiArtifacts(); if (serviceApiArtifacts != null) { - Map copy = serviceApiArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + Map copy = serviceApiArtifacts.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); topologyTemplate.setServiceApiArtifacts(copy); } } @@ -1056,26 +1078,26 @@ public class ModelConverter { Map toscaCapPropMap = new HashMap<>(); if (capabilities != null && !capabilities.isEmpty()) { - capabilities.forEach((s, caps) -> { + capabilities.forEach((s, caps) -> { if (caps != null && !caps.isEmpty()) { - List capList = caps.stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()); + List capList = caps.stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()); populateCapabilityMap(toscaCapMap, toscaCapPropMap, s, caps, capList); } } - ); + ); toscaElement.setCapabilities(toscaCapMap); toscaElement.setCapabilitiesProperties(toscaCapPropMap); } } - private static void convertAttributes(Resource component, NodeType nodeType) { - List attributes = component.getAttributes(); - if (attributes != null) { + private static void convertAttributesToNodeType(Resource component, NodeType nodeType) { + List attributes = component.getAttributes(); + if (CollectionUtils.isNotEmpty(attributes)) { Map attrsByName = attributes.stream() - .collect(Collectors.toMap(AttributeDataDefinition::getName, Function.identity())); + .collect(Collectors.toMap(AttributeDefinition::getName, Function.identity())); nodeType.setAttributes(attrsByName); } } @@ -1086,16 +1108,16 @@ public class ModelConverter { Map toscaReqMap = new HashMap<>(); if (requirements != null && !requirements.isEmpty()) { - requirements.forEach((s, reqs)-> { + requirements.forEach((s, reqs) -> { if (reqs != null && !reqs.isEmpty()) { - List reqList = reqs.stream().map(RequirementDataDefinition::new).collect(Collectors.toList()); + List reqList = reqs.stream().map(RequirementDataDefinition::new).collect(Collectors.toList()); ListRequirementDataDefinition listRequirementDataDefinition = new ListRequirementDataDefinition(reqList); toscaReqMap.put(s, listRequirementDataDefinition); } } - ); + ); nodeType.setRequirements(toscaReqMap); } } @@ -1110,38 +1132,41 @@ public class ModelConverter { } } - public static Map> getCapabilitiesMapFromMapObject(Map toscaCapabilities, Map toscaCapPropMap) { + public static Map> getCapabilitiesMapFromMapObject(Map toscaCapabilities, + Map toscaCapPropMap) { Map> compCap = new HashMap<>(); - if (toscaCapabilities == null || toscaCapabilities.isEmpty()) + if (toscaCapabilities == null || toscaCapabilities.isEmpty()) { return null; - toscaCapabilities.forEach((s, cap)-> { + } + toscaCapabilities.forEach((s, cap) -> { - if (cap != null) { - List capDataList = cap.getListToscaDataDefinition(); + if (cap != null) { + List capDataList = cap.getListToscaDataDefinition(); - if (capDataList != null && !capDataList.isEmpty()) { - List capList = capDataList.stream().map(CapabilityDefinition::new).collect(Collectors.toList()); - compCap.put(s, capList); - } + if (capDataList != null && !capDataList.isEmpty()) { + List capList = capDataList.stream().map(CapabilityDefinition::new).collect(Collectors.toList()); + compCap.put(s, capList); } - } + + } ); if (toscaCapPropMap != null && !toscaCapPropMap.isEmpty()) { - toscaCapPropMap.forEach((s, capProp)-> { - String[] result = s.split(CAP_PROP_DELIM); - if (capProp != null) { - Map capMap = capProp.getMapToscaDataDefinition(); - - if (capMap != null && !capMap.isEmpty()) { - List capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList()); - - List cap = compCap.get(result[0]); - Optional op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst(); - op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList)); - } + toscaCapPropMap.forEach((s, capProp) -> { + String[] result = s.split(CAP_PROP_DELIM); + if (capProp != null) { + Map capMap = capProp.getMapToscaDataDefinition(); + + if (capMap != null && !capMap.isEmpty()) { + List capPropsList = capMap.values().stream().map(ComponentInstanceProperty::new) + .collect(Collectors.toList()); + + List cap = compCap.get(result[0]); + Optional op = cap.stream().filter(c -> c.getName().equals(result[1])).findFirst(); + op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList)); } } + } ); } return compCap; @@ -1151,7 +1176,7 @@ public class ModelConverter { Map toscaGroups = toscaElement.getGroups(); List groupDefinitions = null; if (MapUtils.isNotEmpty(toscaGroups)) { - groupDefinitions = toscaGroups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); + groupDefinitions = toscaGroups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); } component.setGroups(groupDefinitions); } @@ -1160,7 +1185,8 @@ public class ModelConverter { Map policies = toscaElement.getPolicies(); Map policyDefinitions = null; if (MapUtils.isNotEmpty(policies)) { - policyDefinitions = policies.values().stream().map(PolicyDefinition::new).collect(Collectors.toMap(PolicyDefinition::getUniqueId, Function.identity())); + policyDefinitions = policies.values().stream().map(PolicyDefinition::new) + .collect(Collectors.toMap(PolicyDefinition::getUniqueId, Function.identity())); } component.setPolicies(policyDefinitions); } @@ -1170,7 +1196,7 @@ public class ModelConverter { Map groups = new HashMap<>(); if (groupDefinitions != null && groups.isEmpty()) { - groups = groupDefinitions.stream().collect(Collectors.toMap(GroupDefinition::getInvariantName, GroupDefinition::new)); + groups = groupDefinitions.stream().collect(Collectors.toMap(GroupDefinition::getInvariantName, GroupDefinition::new)); } toscaElement.setGroups(groups); } @@ -1179,7 +1205,7 @@ public class ModelConverter { Map policyDefinitions = component.getPolicies(); Map policies = new HashMap<>(); if (MapUtils.isNotEmpty(policyDefinitions)) { - policies = policyDefinitions.values().stream().collect((Collectors.toMap(PolicyDefinition::getUniqueId, PolicyDataDefinition::new))); + policies = policyDefinitions.values().stream().collect((Collectors.toMap(PolicyDefinition::getUniqueId, PolicyDataDefinition::new))); } toscaElement.setPolicies(policies); } @@ -1188,20 +1214,21 @@ public class ModelConverter { Map toscaRequirements = toscaElement.getRequirements(); Map> compReqs = new HashMap<>(); - if (toscaRequirements == null || toscaRequirements.isEmpty()) + if (toscaRequirements == null || toscaRequirements.isEmpty()) { return; - toscaRequirements.forEach((s, req) -> { + } + toscaRequirements.forEach((s, req) -> { if (req != null) { List reqDataList = req.getListToscaDataDefinition(); if (reqDataList != null && !reqDataList.isEmpty()) { - List reqList = reqDataList.stream().map(RequirementDefinition::new).collect(Collectors.toList()); + List reqList = reqDataList.stream().map(RequirementDefinition::new).collect(Collectors.toList()); compReqs.put(s, reqList); } } } - ); + ); component.setRequirements(compReqs); } @@ -1210,48 +1237,40 @@ public class ModelConverter { ComponentTypeEnum componentType = component.getComponentType(); topologyTemplate = new TopologyTemplate(); - if (componentType == ComponentTypeEnum.RESOURCE) { - Resource resource = (Resource) component; - topologyTemplate.setResourceType(resource.getResourceType()); - topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_UUID, resource.getCsarUUID()); - topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_VERSION, resource.getCsarVersion()); - topologyTemplate.setMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM, resource.getImportedToscaChecksum()); - convertTopologyTemplateInterfaces(resource, topologyTemplate); - } - if (componentType == ComponentTypeEnum.SERVICE) { - convertServiceSpecificEntities((Service) component, topologyTemplate); - } - convertCommonToscaData(component, topologyTemplate); - convertArtifacts(component, topologyTemplate); + if (componentType == ComponentTypeEnum.RESOURCE) { + Resource resource = (Resource) component; + topologyTemplate.setResourceType(resource.getResourceType()); + topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_UUID, resource.getCsarUUID()); + topologyTemplate.setMetadataValue(JsonPresentationFields.CSAR_VERSION, resource.getCsarVersion()); + topologyTemplate.setMetadataValue(JsonPresentationFields.IMPORTED_TOSCA_CHECKSUM, resource.getImportedToscaChecksum()); + convertTopologyTemplateInterfaces(resource, topologyTemplate); + } + if (componentType == ComponentTypeEnum.SERVICE) { + convertServiceSpecificEntities((Service) component, topologyTemplate); + } + convertCommonToscaData(component, topologyTemplate); + convertArtifacts(component, topologyTemplate); convertAdditionalInformation(component, topologyTemplate); convertComponentInstances(component, topologyTemplate); - convertInputs(component, topologyTemplate); - convertProperties(component, topologyTemplate); - convertCapabilities(component, topologyTemplate); - convertGroups(component, topologyTemplate); - convertPolicies(component, topologyTemplate); - convertRequirements(component, topologyTemplate); - convertRelationsToComposition(component, topologyTemplate); + convertInputs(component, topologyTemplate); + convertProperties(component, topologyTemplate); + convertAttributesToTopologyTemplate(component, topologyTemplate); + convertCapabilities(component, topologyTemplate); + convertGroups(component, topologyTemplate); + convertPolicies(component, topologyTemplate); + convertRequirements(component, topologyTemplate); + convertRelationsToComposition(component, topologyTemplate); return topologyTemplate; } - private static void convertTopologyTemplateInterfaces(Resource resource, TopologyTemplate topologyTemplate) { - Map interfaces = resource.getInterfaces(); - if (interfaces != null && !interfaces.isEmpty()) { - Map copy = interfaces.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); - topologyTemplate.setInterfaces(copy); - } - } - - private static void convertServiceInterfaces(Service service, TopologyTemplate topologyTemplate) { - Map interfaces = service.getInterfaces(); + private static void convertTopologyTemplateInterfaces(Resource resource, TopologyTemplate topologyTemplate) { + Map interfaces = resource.getInterfaces(); if (interfaces != null && !interfaces.isEmpty()) { Map copy = interfaces.entrySet().stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); + .collect(Collectors.toMap(Map.Entry::getKey, e -> new InterfaceDataDefinition(e.getValue()))); topologyTemplate.setInterfaces(copy); } } @@ -1259,29 +1278,30 @@ public class ModelConverter { private static void convertServiceSpecificEntities(Service service, TopologyTemplate topologyTemplate) { convertServiceMetaData(service, topologyTemplate); convertServiceApiArtifacts(service, topologyTemplate); - convertServicePaths(service,topologyTemplate); - convertServiceInterfaces(topologyTemplate,service); + convertServicePaths(service, topologyTemplate); + convertServiceInterfaces(topologyTemplate, service); } private static void convertServicePaths(Service service, TopologyTemplate topologyTemplate) { Map servicePaths = service.getForwardingPaths(); if (servicePaths != null && !servicePaths.isEmpty()) { - Map copy = servicePaths.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); + Map copy = servicePaths.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new ForwardingPathDataDefinition(e.getValue()))); topologyTemplate.setForwardingPaths(copy); } } - private static void convertServiceMetaData(Service service, TopologyTemplate topologyTemplate) { - if (service.getDistributionStatus() != null) { - topologyTemplate.setMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS, - service.getDistributionStatus().name()); - } - topologyTemplate.setMetadataValue(JsonPresentationFields.PROJECT_CODE, service.getProjectCode()); - topologyTemplate.setMetadataValue(JsonPresentationFields.ECOMP_GENERATED_NAMING, - service.isEcompGeneratedNaming()); - topologyTemplate.setMetadataValue(JsonPresentationFields.NAMING_POLICY, service.getNamingPolicy()); - topologyTemplate.setMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT, service.getEnvironmentContext()); - topologyTemplate.setMetadataValue(JsonPresentationFields.INSTANTIATION_TYPE, service.getInstantiationType()); + private static void convertServiceMetaData(Service service, TopologyTemplate topologyTemplate) { + if (service.getDistributionStatus() != null) { + topologyTemplate.setMetadataValue(JsonPresentationFields.DISTRIBUTION_STATUS, + service.getDistributionStatus().name()); + } + topologyTemplate.setMetadataValue(JsonPresentationFields.PROJECT_CODE, service.getProjectCode()); + topologyTemplate.setMetadataValue(JsonPresentationFields.ECOMP_GENERATED_NAMING, + service.isEcompGeneratedNaming()); + topologyTemplate.setMetadataValue(JsonPresentationFields.NAMING_POLICY, service.getNamingPolicy()); + topologyTemplate.setMetadataValue(JsonPresentationFields.ENVIRONMENT_CONTEXT, service.getEnvironmentContext()); + topologyTemplate.setMetadataValue(JsonPresentationFields.INSTANTIATION_TYPE, service.getInstantiationType()); } @@ -1298,8 +1318,9 @@ public class ModelConverter { compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), compositionDataDefinition); } - Map relations = componentInstancesRelations.stream().flatMap(x -> convertRelationToToscaRelation(x).stream()).filter(i -> i.getUniqueId() != null) - .collect(Collectors.toMap(RelationshipInstDataDefinition::getUniqueId, Function.identity())); + Map relations = componentInstancesRelations.stream() + .flatMap(x -> convertRelationToToscaRelation(x).stream()).filter(i -> i.getUniqueId() != null) + .collect(Collectors.toMap(RelationshipInstDataDefinition::getUniqueId, Function.identity())); compositionDataDefinition.setRelations(relations); } } @@ -1308,41 +1329,60 @@ public class ModelConverter { List inputsList = component.getInputs(); if (inputsList != null && !inputsList.isEmpty()) { - Map inputsMap = inputsList.stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); + Map inputsMap = inputsList.stream().map(PropertyDataDefinition::new) + .collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity())); topologyTemplate.setInputs(inputsMap); } } - private static void convertInputs(TopologyTemplate topologyTemplate, Component component) { - Map inputsMap = topologyTemplate.getInputs(); - if (inputsMap != null && !inputsMap.isEmpty()) { - List inputsList = inputsMap.values() - .stream() - .map(InputDefinition::new) - .collect(Collectors.toList()); - component.setInputs(inputsList); - } - } + private static void convertInputs(TopologyTemplate topologyTemplate, Component component) { + Map inputsMap = topologyTemplate.getInputs(); + if (inputsMap != null && !inputsMap.isEmpty()) { + List inputsList = inputsMap.values() + .stream() + .map(InputDefinition::new) + .collect(Collectors.toList()); + component.setInputs(inputsList); + } + } + + private static void convertProperties(Component component, TopologyTemplate topologyTemplate) { + List propertiesList = component.getProperties(); + if (propertiesList != null && !propertiesList.isEmpty()) { + Map propertiesMap = propertiesList.stream() + .map(i -> new PropertyDataDefinition(i)).collect(Collectors.toMap(i -> i.getName(), i -> i)); + topologyTemplate.setProperties(propertiesMap); + } + } - private static void convertProperties(Component component, TopologyTemplate topologyTemplate) { - List propertiesList = component.getProperties(); - if (propertiesList != null && !propertiesList.isEmpty()) { - Map propertiesMap = propertiesList.stream().map(i -> new PropertyDataDefinition(i)).collect(Collectors.toMap(i -> i.getName(), i -> i)); - topologyTemplate.setProperties(propertiesMap); - } + private static void convertAttributesToTopologyTemplate(final Component component, final TopologyTemplate topologyTemplate) { + final List attributes = component.getAttributes(); + if (CollectionUtils.isNotEmpty(attributes)) { + final Map attributeDataDefinitionMap = attributes.stream() + .map(AttributeDataDefinition::new).collect(Collectors.toMap(AttributeDataDefinition::getName, i -> i)); + topologyTemplate.setAttributes(attributeDataDefinitionMap); + } + } - } + private static void convertProperties(TopologyTemplate topologyTemplate, Component component) { + Map propertiesMap = topologyTemplate.getProperties(); + if (propertiesMap != null && !propertiesMap.isEmpty()) { + Map copy = propertiesMap.entrySet().stream() + .collect(Collectors.toMap(entry -> entry.getKey(), entry -> new PropertyDefinition + (entry.getValue()))); + component.setProperties(new ArrayList<>(copy.values())); + } + } - private static void convertProperties(TopologyTemplate topologyTemplate, Component component) { - Map proeprtiesMap = topologyTemplate.getProperties(); - if (proeprtiesMap != null && !proeprtiesMap.isEmpty()) { - Map copy = proeprtiesMap.entrySet().stream() - .collect(Collectors.toMap(entry -> entry.getKey(), entry -> new PropertyDefinition - (entry.getValue()))); - component.setProperties(new ArrayList<>(copy.values())); - } - } + private static void convertAttributesToComponent(final TopologyTemplate topologyTemplate, final Component component) { + final Map attributes = topologyTemplate.getAttributes(); + if (MapUtils.isNotEmpty(attributes)) { + Map copy = attributes.entrySet().stream() + .collect(Collectors.toMap(entry -> entry.getKey(), entry -> new AttributeDefinition(entry.getValue()))); + component.setAttributes(new ArrayList<>(copy.values())); + } + } private static void convertDataTypes(final ToscaElement toscaElement, final Component component) { final Map dataTypeDataMap = toscaElement.getDataTypes(); @@ -1365,7 +1405,6 @@ public class ModelConverter { } } - private static void convertCommonToscaData(Component component, ToscaElement toscaElement) { toscaElement.setUUID(component.getUUID()); toscaElement.setUniqueId(component.getUniqueId()); @@ -1398,24 +1437,25 @@ public class ModelConverter { toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_NAME, ((Resource) component).getVendorName()); toscaElement.setMetadataValue(JsonPresentationFields.VENDOR_RELEASE, ((Resource) component).getVendorRelease()); // field isn't mandatory , but shouldn't be null(should be an empty string instead) - if (((Resource) component).getResourceVendorModelNumber() != null){ - toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ((Resource) component).getResourceVendorModelNumber()); + if (((Resource) component).getResourceVendorModelNumber() != null) { + toscaElement + .setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ((Resource) component).getResourceVendorModelNumber()); } else { toscaElement.setMetadataValue(JsonPresentationFields.RESOURCE_VENDOR_MODEL_NUMBER, ""); } } else if (component.getComponentType() == ComponentTypeEnum.SERVICE) { // field isn't mandatory , but shouldn't be null(should be an empty string instead) - if (((Service) component).getServiceType() != null){ + if (((Service) component).getServiceType() != null) { toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ((Service) component).getServiceType()); } else { toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_TYPE, ""); } - if (((Service) component).getServiceRole() != null){ + if (((Service) component).getServiceRole() != null) { toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ((Service) component).getServiceRole()); } else { toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_ROLE, ""); } - if (((Service) component).getServiceFunction() != null){ + if (((Service) component).getServiceFunction() != null) { toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_FUNCTION, ((Service) component).getServiceFunction()); } else { toscaElement.setMetadataValue(JsonPresentationFields.SERVICE_FUNCTION, ""); @@ -1428,8 +1468,8 @@ public class ModelConverter { toscaElement.setMetadataValue(JsonPresentationFields.TAGS, component.getTags()); toscaElement.setMetadataValue(JsonPresentationFields.INVARIANT_UUID, component.getInvariantUUID()); toscaElement.setMetadataValue(JsonPresentationFields.CONTACT_ID, component.getContactId()); - for (final String key: component.getCategorySpecificMetadata().keySet()) { - toscaElement.setMetadataValue(key, component.getCategorySpecificMetadata().get(key)); + for (final String key : component.getCategorySpecificMetadata().keySet()) { + toscaElement.setMetadataValue(key, component.getCategorySpecificMetadata().get(key)); } final List dataTypes = component.getDataTypes(); @@ -1449,23 +1489,36 @@ public class ModelConverter { String key = entry.getKey(); currComponentInstance = new ComponentInstance(topologyTemplate.getComponentInstances().get(key)); if (topologyTemplate.getInstGroups() != null && topologyTemplate.getInstGroups().containsKey(key)) { - List groupInstances = topologyTemplate.getInstGroups().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new GroupInstance(e.getValue())).collect(Collectors.toList()); + List groupInstances = topologyTemplate.getInstGroups().get(key).getMapToscaDataDefinition().entrySet().stream() + .map(e -> new GroupInstance(e.getValue())).collect(Collectors.toList()); currComponentInstance.setGroupInstances(groupInstances); } setComponentInstanceSource(currComponentInstance, component); - if(MapUtils.isNotEmpty(nodeFilterComponents) && nodeFilterComponents.containsKey(key)){ + if (MapUtils.isNotEmpty(nodeFilterComponents) && nodeFilterComponents.containsKey(key)) { currComponentInstance.setNodeFilter(nodeFilterComponents.get(key)); } - if(topologyTemplate.getInstProperties() != null && topologyTemplate.getInstProperties().containsKey(key) && topologyTemplate.getInstProperties().get(key) != null ){ - List instanceProps = topologyTemplate.getInstProperties().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new PropertyDefinition(e.getValue())).collect(Collectors.toList()); + if (topologyTemplate.getInstProperties() != null && topologyTemplate.getInstProperties().containsKey(key) + && topologyTemplate.getInstProperties().get(key) != null) { + List instanceProps = topologyTemplate.getInstProperties().get(key).getMapToscaDataDefinition().entrySet().stream() + .map(e -> new PropertyDefinition(e.getValue())).collect(Collectors.toList()); currComponentInstance.setProperties(instanceProps); } - if(topologyTemplate.getInstInputs() != null && topologyTemplate.getInstInputs().containsKey(key) && topologyTemplate.getInstInputs().get(key) != null ){ - List instanceInputs = topologyTemplate.getInstInputs().get(key).getMapToscaDataDefinition().entrySet().stream().map(e -> new InputDefinition(e.getValue())).collect(Collectors.toList()); + if (topologyTemplate.getInstInputs() != null && topologyTemplate.getInstInputs().containsKey(key) + && topologyTemplate.getInstInputs().get(key) != null) { + List instanceInputs = topologyTemplate.getInstInputs().get(key).getMapToscaDataDefinition().entrySet().stream() + .map(e -> new InputDefinition(e.getValue())).collect(Collectors.toList()); currComponentInstance.setInputs(instanceInputs); } - if(topologyTemplate.getComponentInstInterfaces() != null && topologyTemplate.getComponentInstInterfaces().containsKey(key) && topologyTemplate.getComponentInstInterfaces().get(key) != null ){ - Map interfacesMap = topologyTemplate.getComponentInstInterfaces().get(key).getMapToscaDataDefinition().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + final Map instAttributes = topologyTemplate.getInstAttributes(); + if (instAttributes != null && instAttributes.containsKey(key) && instAttributes.get(key) != null) { + currComponentInstance.setAttributes( + instAttributes.get(key).getMapToscaDataDefinition().values().stream().map(AttributeDefinition::new) + .collect(Collectors.toList())); + } + if (topologyTemplate.getComponentInstInterfaces() != null && topologyTemplate.getComponentInstInterfaces().containsKey(key) + && topologyTemplate.getComponentInstInterfaces().get(key) != null) { + Map interfacesMap = topologyTemplate.getComponentInstInterfaces().get(key).getMapToscaDataDefinition().entrySet() + .stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); currComponentInstance.setInterfaces(interfacesMap); } componentInstances.add(currComponentInstance); @@ -1474,7 +1527,8 @@ public class ModelConverter { component.setComponentInstances(componentInstances); } - public static List getComponentInstancesFromMapObject(Map componentInstancesDefinitionMap, Component component) { + public static List getComponentInstancesFromMapObject( + Map componentInstancesDefinitionMap, Component component) { List componentInstances = new ArrayList<>(); ComponentInstance currComponentInstance; for (Map.Entry entry : componentInstancesDefinitionMap.entrySet()) { @@ -1487,13 +1541,12 @@ public class ModelConverter { } private static void setComponentInstanceSource(ComponentInstance currComponentInstance, Component component) { - if (Objects.isNull(currComponentInstance.getCreatedFrom())){ - if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())){ + if (Objects.isNull(currComponentInstance.getCreatedFrom())) { + if (ComponentTypeEnum.RESOURCE.equals(component.getComponentType())) { Resource resource = (Resource) component; - if (isFromCsar(resource)){ + if (isFromCsar(resource)) { currComponentInstance.setCreatedFrom(CreatedFrom.CSAR); - } - else { + } else { currComponentInstance.setCreatedFrom(CreatedFrom.UI); } } @@ -1511,7 +1564,8 @@ public class ModelConverter { for (Entry entry : topologyTemplate.getInstInputs().entrySet()) { if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { String key = entry.getKey(); - List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream().map(e -> new ComponentInstanceInput(e.getValue())).collect(Collectors.toList()); + List componentInstanceAttributes = entry.getValue().getMapToscaDataDefinition().entrySet().stream() + .map(e -> new ComponentInstanceInput(e.getValue())).collect(Collectors.toList()); inputs.put(key, componentInstanceAttributes); } } @@ -1544,7 +1598,7 @@ public class ModelConverter { String key = entry.getKey(); List componentInstanceAttributes = entry.getValue() .getMapToscaDataDefinition().entrySet().stream() - .map(e -> new ComponentInstanceAttribute(new ComponentInstanceAttribute(e.getValue()))) + .map(e -> new ComponentInstanceAttribute(new AttributeDefinition(e.getValue()))) .collect(Collectors.toList()); attributes.put(key, componentInstanceAttributes); } @@ -1559,23 +1613,22 @@ public class ModelConverter { if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { String key = entry.getKey(); List componentInstanceInterfaces = entry.getValue() - .getMapToscaDataDefinition().entrySet().stream().map(e -> new - ComponentInstanceInterface(e.getKey(), e.getValue())) - .collect(Collectors.toList()); + .getMapToscaDataDefinition().entrySet().stream().map(e -> new + ComponentInstanceInterface(e.getKey(), e.getValue())) + .collect(Collectors.toList()); interfaces.put(key, componentInstanceInterfaces); } } component.setComponentInstancesInterfaces(interfaces); - } - else if (topologyTemplate.getComponentInstInterfaces() != null) { + } else if (topologyTemplate.getComponentInstInterfaces() != null) { Map> interfaces = new HashMap<>(); for (Map.Entry entry : topologyTemplate.getComponentInstInterfaces().entrySet()) { if (entry.getValue() != null && entry.getValue().getMapToscaDataDefinition() != null) { String key = entry.getKey(); List componentInstanceInterfaces = entry.getValue() - .getMapToscaDataDefinition().entrySet().stream().map(e -> new - ComponentInstanceInterface(e.getKey(), e.getValue())) - .collect(Collectors.toList()); + .getMapToscaDataDefinition().entrySet().stream().map(e -> new + ComponentInstanceInterface(e.getKey(), e.getValue())) + .collect(Collectors.toList()); interfaces.put(key, componentInstanceInterfaces); } } @@ -1593,7 +1646,7 @@ public class ModelConverter { String key = entry.getKey(); List componentInstanceAttributes = entry.getValue() .getMapToscaDataDefinition().entrySet().stream() - .map(e -> new ComponentInstanceAttribute(new ComponentInstanceAttribute(e.getValue()))) + .map(e -> new ComponentInstanceAttribute(new AttributeDefinition(e.getValue()))) .collect(Collectors.toList()); attributes.put(key, componentInstanceAttributes); } @@ -1607,15 +1660,17 @@ public class ModelConverter { if (topologyTemplate.getCalculatedRequirements() != null) { // Requirements of component organized by capability - Map> instanceRequiermentsFromMapObject = getInstanceRequirementsFromMapObject(topologyTemplate.getCalculatedRequirements(), component); + Map> instanceRequiermentsFromMapObject = getInstanceRequirementsFromMapObject( + topologyTemplate.getCalculatedRequirements(), component); component.setRequirements(instanceRequiermentsFromMapObject); } } - public static Map> getInstanceRequirementsFromMapObject(Map mapListRequirements, Component component) { + public static Map> getInstanceRequirementsFromMapObject( + Map mapListRequirements, Component component) { // Requirements of component organized by capability Map> instancesRequirements = new HashMap<>(); - if (mapListRequirements!= null) { + if (mapListRequirements != null) { Map instancesMap = new HashMap<>(); for (ComponentInstance currInstance : component.getComponentInstances()) { instancesMap.put(currInstance.getUniqueId(), currInstance); @@ -1626,10 +1681,11 @@ public class ModelConverter { // Requirements of instance organized by capability Map capsMapList = entry.getValue().getMapToscaDataDefinition(); - if(capsMapList != null) { + if (capsMapList != null) { for (Entry entryTypeList : capsMapList.entrySet()) { String capabilityType = entryTypeList.getKey(); - List caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(RequirementDefinition::new).collect(Collectors.toList()); + List caps = entryTypeList.getValue().getListToscaDataDefinition().stream() + .map(RequirementDefinition::new).collect(Collectors.toList()); if (instancesRequirements.containsKey(capabilityType)) { instancesRequirements.get(capabilityType).addAll(caps); } else { @@ -1644,7 +1700,7 @@ public class ModelConverter { } component.setRequirements(instancesRequirements); } - return instancesRequirements; + return instancesRequirements; } public static void setComponentInstancesCapabilitiesToComponentAndCI(TopologyTemplate topologyTemplate, Component component) { @@ -1664,10 +1720,11 @@ public class ModelConverter { // capabilities of instance organized by type Map capsMapList = entry.getValue().getMapToscaDataDefinition(); - if(capsMapList != null) { + if (capsMapList != null) { for (Entry entryTypeList : capsMapList.entrySet()) { String capabilityType = entryTypeList.getKey(); - List caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, instanceId, calculatedCapProperties)).collect(Collectors.toList()); + List caps = entryTypeList.getValue().getListToscaDataDefinition().stream() + .map(cap -> mergeInstCapabiltyWithProperty(cap, instanceId, calculatedCapProperties)).collect(Collectors.toList()); if (instancesCapabilities.containsKey(capabilityType)) { instancesCapabilities.get(capabilityType).addAll(caps); } else { @@ -1675,7 +1732,8 @@ public class ModelConverter { } ComponentInstance instance = instancesMap.get(instanceId); if (instance == null) { - log.error("instance is null for id {} entry {}", instanceId, entry.getValue().getToscaPresentationValue(JsonPresentationFields.NAME)); + log.error("instance is null for id {} entry {}", instanceId, + entry.getValue().getToscaPresentationValue(JsonPresentationFields.NAME)); } else { if (MapUtils.isEmpty(instance.getCapabilities())) { instance.setCapabilities(new HashMap<>()); @@ -1694,33 +1752,33 @@ public class ModelConverter { Map capabilitiesProperties = topologyTemplate.getCapabilitiesProperties(); Map> allCapabilities = new HashMap<>(); - if(MapUtils.isNotEmpty(capabilities)) { + if (MapUtils.isNotEmpty(capabilities)) { allCapabilities.putAll(groupCapabilityByType(capabilities)); } - if(MapUtils.isNotEmpty(capabilitiesProperties)) { - capabilitiesProperties.forEach((s, capProp)-> { - String[] result = s.split(CAP_PROP_DELIM); - if (capProp != null) { - Map capMap = capProp.getMapToscaDataDefinition(); + if (MapUtils.isNotEmpty(capabilitiesProperties)) { + capabilitiesProperties.forEach((s, capProp) -> { + String[] result = s.split(CAP_PROP_DELIM); + if (capProp != null) { + Map capMap = capProp.getMapToscaDataDefinition(); - if (MapUtils.isNotEmpty(capMap)) { - List capPropsList = capMap.values().stream() - .map(ComponentInstanceProperty::new).collect(Collectors.toList()); + if (MapUtils.isNotEmpty(capMap)) { + List capPropsList = capMap.values().stream() + .map(ComponentInstanceProperty::new).collect(Collectors.toList()); - List cap = allCapabilities.get(result[0]); - if (cap !=null) { - Optional op = cap.stream().filter(c -> c.getName() - .equals(result[1])).findFirst(); - op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList)); - } + List cap = allCapabilities.get(result[0]); + if (cap != null) { + Optional op = cap.stream().filter(c -> c.getName() + .equals(result[1])).findFirst(); + op.ifPresent(capabilityDefinition -> capabilityDefinition.setProperties(capPropsList)); } } } + } ); } Map> componentCapabilities = component.getCapabilities(); - if(MapUtils.isNotEmpty(componentCapabilities)) { + if (MapUtils.isNotEmpty(componentCapabilities)) { mergeCapabilityMap(allCapabilities, componentCapabilities); } component.setCapabilities(allCapabilities); @@ -1729,7 +1787,7 @@ public class ModelConverter { private static void mergeCapabilityMap(Map> map1, Map> map2) { map1.forEach((key1, val1) -> map2.forEach((key2, val2) -> { - if(key1.equals(key2)) { + if (key1.equals(key2)) { val2.addAll(val1); } })); @@ -1737,23 +1795,23 @@ public class ModelConverter { } private static Map> groupCapabilityByType(Map capabilities) { - Map> groupedCapabilities = new HashMap<>(); + ListCapabilityDataDefinition> capabilities) { + Map> groupedCapabilities = new HashMap<>(); Set typesSet = new HashSet<>(); List allCapabilityDefinitions = new ArrayList<>(); for (Entry capabilitiesEntry : capabilities.entrySet()) { - typesSet.addAll( capabilitiesEntry.getValue().getListToscaDataDefinition() - .stream().map(CapabilityDataDefinition::getType).collect(Collectors.toSet())); + typesSet.addAll(capabilitiesEntry.getValue().getListToscaDataDefinition() + .stream().map(CapabilityDataDefinition::getType).collect(Collectors.toSet())); allCapabilityDefinitions.addAll(capabilitiesEntry.getValue().getListToscaDataDefinition() - .stream().map(CapabilityDefinition::new).collect(Collectors.toList())); + .stream().map(CapabilityDefinition::new).collect(Collectors.toList())); } - for(String capType : typesSet) { + for (String capType : typesSet) { groupedCapabilities.put(capType, allCapabilityDefinitions.stream() - .filter(capabilityDefinition -> capabilityDefinition.getType() - .equals(capType)).collect(Collectors.toList())); + .filter(capabilityDefinition -> capabilityDefinition.getType() + .equals(capType)).collect(Collectors.toList())); } return groupedCapabilities; } @@ -1761,8 +1819,8 @@ public class ModelConverter { private static void setRequirementsToComponent(TopologyTemplate topologyTemplate, Component component) { Map requirements = topologyTemplate.getRequirements(); Map> componentRequirements = component.getRequirements(); - if(MapUtils.isNotEmpty(requirements)) { - if(componentRequirements == null) { + if (MapUtils.isNotEmpty(requirements)) { + if (componentRequirements == null) { componentRequirements = new HashMap<>(); } componentRequirements.putAll(groupRequirementByType(requirements)); @@ -1771,107 +1829,116 @@ public class ModelConverter { } private static Map> groupRequirementByType(Map requirements) { - Map> groupedRequirement = new HashMap<>(); + ListRequirementDataDefinition> requirements) { + Map> groupedRequirement = new HashMap<>(); Set typesSet = new HashSet<>(); List allRequirements = new ArrayList<>(); for (Entry requirementsEntry : requirements.entrySet()) { - typesSet.addAll( requirementsEntry.getValue().getListToscaDataDefinition() - .stream().map(RequirementDataDefinition::getCapability).collect(Collectors.toSet())); + typesSet.addAll(requirementsEntry.getValue().getListToscaDataDefinition() + .stream().map(RequirementDataDefinition::getCapability).collect(Collectors.toSet())); allRequirements.addAll(requirementsEntry.getValue().getListToscaDataDefinition() - .stream().map(RequirementDefinition::new).collect(Collectors.toList())); + .stream().map(RequirementDefinition::new).collect(Collectors.toList())); } - for(String capType : typesSet) { + for (String capType : typesSet) { groupedRequirement.put(capType, allRequirements.stream().filter(requirementDefinition -> - requirementDefinition.getCapability().equals(capType)).collect(Collectors.toList())); + requirementDefinition.getCapability().equals(capType)).collect(Collectors.toList())); } return groupedRequirement; } - private static void setCapabilitiesToComponentAndGroups(TopologyTemplate topologyTemplate, Component component) { - Map calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); - - if (capabilitiesAndGroupsExist(topologyTemplate, component)) { - Map groupsMap = component.getGroups().stream().collect(Collectors.toMap(GroupDefinition::getUniqueId,Function.identity())); - - for (Map.Entry entry : topologyTemplate.getCalculatedCapabilities().entrySet()) { - findSetCapabilitiesToComponentAndGroup(calculatedCapProperties, component, groupsMap, entry); - } - } - } - - private static boolean capabilitiesAndGroupsExist(TopologyTemplate topologyTemplate, Component component) { - return MapUtils.isNotEmpty(topologyTemplate.getCalculatedCapabilities()) && CollectionUtils.isNotEmpty(component.getGroups()); - } - - private static void findSetCapabilitiesToComponentAndGroup(Map calculatedCapProperties, Component component, Map groupsMap, Map.Entry entry) { - - String uniqueId = entry.getKey(); - if(groupsMap.containsKey(uniqueId)){ - setCapabilitiesToComponentAndGroup(calculatedCapProperties, component, entry, groupsMap.get(uniqueId)); - } else { - log.warn("The group with uniqueId {} was not found", uniqueId); - } - } - - private static void setCapabilitiesToComponentAndGroup(Map calculatedCapProperties, Component component, Map.Entry entry, GroupDefinition group) { - - for (Entry entryTypeList : entry.getValue().getMapToscaDataDefinition().entrySet()) { - String capabilityType = entryTypeList.getKey(); - List caps = entryTypeList.getValue().getListToscaDataDefinition().stream().map(cap -> mergeInstCapabiltyWithProperty(cap, group.getUniqueId(), calculatedCapProperties)).collect(Collectors.toList()); - if (component.getCapabilities().containsKey(capabilityType)) { - component.getCapabilities().get(capabilityType).addAll(caps); - } else { - component.getCapabilities().put(capabilityType, caps); - } - group.getCapabilities().put(capabilityType, Lists.newArrayList(caps)); - } - } - - private static CapabilityDefinition mergeInstCapabiltyWithProperty(CapabilityDataDefinition cap, String ownerId, Map calculatedCapProperties) { + Map calculatedCapProperties = topologyTemplate.getCalculatedCapabilitiesProperties(); + + if (capabilitiesAndGroupsExist(topologyTemplate, component)) { + Map groupsMap = component.getGroups().stream() + .collect(Collectors.toMap(GroupDefinition::getUniqueId, Function.identity())); + + for (Map.Entry entry : topologyTemplate.getCalculatedCapabilities().entrySet()) { + findSetCapabilitiesToComponentAndGroup(calculatedCapProperties, component, groupsMap, entry); + } + } + } + + private static boolean capabilitiesAndGroupsExist(TopologyTemplate topologyTemplate, Component component) { + return MapUtils.isNotEmpty(topologyTemplate.getCalculatedCapabilities()) && CollectionUtils.isNotEmpty(component.getGroups()); + } + + private static void findSetCapabilitiesToComponentAndGroup(Map calculatedCapProperties, Component component, + Map groupsMap, + Map.Entry entry) { + + String uniqueId = entry.getKey(); + if (groupsMap.containsKey(uniqueId)) { + setCapabilitiesToComponentAndGroup(calculatedCapProperties, component, entry, groupsMap.get(uniqueId)); + } else { + log.warn("The group with uniqueId {} was not found", uniqueId); + } + } + + private static void setCapabilitiesToComponentAndGroup(Map calculatedCapProperties, Component component, + Map.Entry entry, GroupDefinition group) { + + for (Entry entryTypeList : entry.getValue().getMapToscaDataDefinition().entrySet()) { + String capabilityType = entryTypeList.getKey(); + List caps = entryTypeList.getValue().getListToscaDataDefinition().stream() + .map(cap -> mergeInstCapabiltyWithProperty(cap, group.getUniqueId(), calculatedCapProperties)).collect(Collectors.toList()); + if (component.getCapabilities().containsKey(capabilityType)) { + component.getCapabilities().get(capabilityType).addAll(caps); + } else { + component.getCapabilities().put(capabilityType, caps); + } + group.getCapabilities().put(capabilityType, Lists.newArrayList(caps)); + } + } + + private static CapabilityDefinition mergeInstCapabiltyWithProperty(CapabilityDataDefinition cap, String ownerId, + Map calculatedCapProperties) { CapabilityDefinition capability = new CapabilityDefinition(cap); if (calculatedCapProperties != null) { - MapCapabilityProperty mapOfMapPropertiesDataDefinition = calculatedCapProperties.get(ownerId); + MapCapabilityProperty mapOfMapPropertiesDataDefinition = calculatedCapProperties.get(ownerId); if (mapOfMapPropertiesDataDefinition != null && mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition() != null) { Map toscaCapPropMap = mapOfMapPropertiesDataDefinition.getMapToscaDataDefinition(); - toscaCapPropMap.forEach(( keyPath, capProp)-> findConvertSetProperties(cap, ownerId, capability, keyPath, capProp)); - } - } - return capability; - } - - private static void findConvertSetProperties(CapabilityDataDefinition cap, String primaryPathKey, CapabilityDefinition capability, String path, MapPropertiesDataDefinition capProp) { - // format key of capability properties : - // VF instance in service : instanceId#ownerId#type#capName - // VFC instance in VF : instanceId#type#capName -> instanceId=ownerId - // Group in service : groupName#ownerId#type#capName - // Group in VF : groupName#type#capName -> groupName=ownerId - String[] result = path.split(CAP_PROP_DELIM); - if (result.length < 4) { - log.debug("wrong key format for capabilty, key {}", capProp); - return; - } - if (relatedPropertiesExist(cap, primaryPathKey, capProp, result)) { - capability.setProperties(capProp.getMapToscaDataDefinition().values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList())); - } - } - - private static boolean relatedPropertiesExist(CapabilityDataDefinition cap, String primaryPathKey, MapPropertiesDataDefinition capProp, String[] result) { - return capProp != null && MapUtils.isNotEmpty(capProp.getMapToscaDataDefinition()) && areRelatedProperties(cap, primaryPathKey, result); - } - - private static boolean areRelatedProperties(CapabilityDataDefinition cap, String primaryPathKey, String[] result) { - int primaryKeyIndex = 0; - int ownerIndex = 1; - int typeIndex = result.length - 2; - int nameIndex = result.length - 1; - return result[typeIndex].equals(cap.getType()) && result[nameIndex].equals(cap.getName()) && cap.getOwnerId().equals(result[ownerIndex]) && primaryPathKey.equals(result[primaryKeyIndex]); + toscaCapPropMap.forEach((keyPath, capProp) -> findConvertSetProperties(cap, ownerId, capability, keyPath, capProp)); + } + } + return capability; + } + + private static void findConvertSetProperties(CapabilityDataDefinition cap, String primaryPathKey, CapabilityDefinition capability, String path, + MapPropertiesDataDefinition capProp) { + // format key of capability properties : + // VF instance in service : instanceId#ownerId#type#capName + // VFC instance in VF : instanceId#type#capName -> instanceId=ownerId + // Group in service : groupName#ownerId#type#capName + // Group in VF : groupName#type#capName -> groupName=ownerId + String[] result = path.split(CAP_PROP_DELIM); + if (result.length < 4) { + log.debug("wrong key format for capabilty, key {}", capProp); + return; + } + if (relatedPropertiesExist(cap, primaryPathKey, capProp, result)) { + capability.setProperties( + capProp.getMapToscaDataDefinition().values().stream().map(ComponentInstanceProperty::new).collect(Collectors.toList())); + } + } + + private static boolean relatedPropertiesExist(CapabilityDataDefinition cap, String primaryPathKey, MapPropertiesDataDefinition capProp, + String[] result) { + return capProp != null && MapUtils.isNotEmpty(capProp.getMapToscaDataDefinition()) && areRelatedProperties(cap, primaryPathKey, result); + } + + private static boolean areRelatedProperties(CapabilityDataDefinition cap, String primaryPathKey, String[] result) { + int primaryKeyIndex = 0; + int ownerIndex = 1; + int typeIndex = result.length - 2; + int nameIndex = result.length - 1; + return result[typeIndex].equals(cap.getType()) && result[nameIndex].equals(cap.getName()) && cap.getOwnerId().equals(result[ownerIndex]) + && primaryPathKey.equals(result[primaryKeyIndex]); } private static void setComponentInstancesToTopologyTemplate(Component component, TopologyTemplate topologyTemplate) { @@ -1884,7 +1951,8 @@ public class ModelConverter { if (instance.getGroupInstances() != null) { MapGroupsDataDefinition groupsMap = new MapGroupsDataDefinition(); - groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(GroupInstanceDataDefinition::new).collect(Collectors.toMap(GroupInstanceDataDefinition::getName, Function.identity()))); + groupsMap.setMapToscaDataDefinition(instance.getGroupInstances().stream().map(GroupInstanceDataDefinition::new) + .collect(Collectors.toMap(GroupInstanceDataDefinition::getName, Function.identity()))); if (topologyTemplate.getInstGroups() == null) { topologyTemplate.setInstGroups(new HashMap<>()); } @@ -1905,7 +1973,8 @@ public class ModelConverter { for (Entry> entry : component.getComponentInstancesInputs().entrySet()) { inputsMap = new MapPropertiesDataDefinition(); - inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); + inputsMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new) + .collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); topologyTemplate.getInstInputs().put(entry.getKey(), inputsMap); } @@ -1920,7 +1989,8 @@ public class ModelConverter { for (Entry> entry : component.getComponentInstancesProperties().entrySet()) { propertiesMap = new MapPropertiesDataDefinition(); - propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); + propertiesMap.setMapToscaDataDefinition(entry.getValue().stream().map(PropertyDataDefinition::new) + .collect(Collectors.toMap(PropertyDataDefinition::getName, Function.identity()))); topologyTemplate.getInstProperties().put(entry.getKey(), propertiesMap); } @@ -1937,14 +2007,16 @@ public class ModelConverter { for (ComponentInstance ci : componentInstances) { Map artifacts = ci.getArtifacts(); if (artifacts != null) { - Map mapToscaDataDefinitionArtifact = artifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + Map mapToscaDataDefinitionArtifact = artifacts.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); MapArtifactDataDefinition insArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionArtifact); topologyTemplate.getInstanceArtifacts().put(ci.getUniqueId(), insArtifact); } Map deplArtifacts = ci.getDeploymentArtifacts(); if (deplArtifacts != null) { - Map mapToscaDataDefinitionDepArtifact = deplArtifacts.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); + Map mapToscaDataDefinitionDepArtifact = deplArtifacts.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new ArtifactDataDefinition(e.getValue()))); MapArtifactDataDefinition insDepArtifact = new MapArtifactDataDefinition(mapToscaDataDefinitionDepArtifact); topologyTemplate.getInstDeploymentArtifacts().put(ci.getUniqueId(), insDepArtifact); } @@ -1956,13 +2028,12 @@ public class ModelConverter { if (component.getComponentInstancesAttributes() != null) { topologyTemplate.setInstAttributes(new HashMap<>()); - MapAttributesDataDefinition attributesMap; - for (Entry> entry : component.getComponentInstancesAttributes() - .entrySet()) { - attributesMap = new MapAttributesDataDefinition(); + + for (Entry> entry : component.getComponentInstancesAttributes().entrySet()) { + final MapAttributesDataDefinition attributesMap = new MapAttributesDataDefinition(); attributesMap.setMapToscaDataDefinition(entry.getValue().stream().map(AttributeDefinition::new) - .collect(Collectors.toMap(AttributeDataDefinition::getName, Function.identity(),(entity1,entity2) -> entity1))); + .collect(Collectors.toMap(AttributeDefinition::getName, Function.identity(), (entity1, entity2) -> entity1))); topologyTemplate.getInstAttributes().put(entry.getKey(), attributesMap); } @@ -1972,17 +2043,17 @@ public class ModelConverter { public static ComponentMetadataData convertToComponentMetadata(GraphVertex vertex) { ComponentMetadataData metadata; switch (vertex.getType()) { - case SERVICE: - metadata = new ServiceMetadataData(new GraphPropertiesDictionaryExtractor(vertex.getMetadataJson())); - break; - case RESOURCE: - metadata = new ResourceMetadataData(new GraphPropertiesDictionaryExtractor(vertex.getMetadataJson())); - break; - case PRODUCT: - metadata = new ProductMetadataData(new GraphPropertiesDictionaryExtractor(vertex.getMetadataJson())); - break; - default: - throw new StorageException(JanusGraphOperationStatus.INVALID_TYPE); + case SERVICE: + metadata = new ServiceMetadataData(new GraphPropertiesDictionaryExtractor(vertex.getMetadataJson())); + break; + case RESOURCE: + metadata = new ResourceMetadataData(new GraphPropertiesDictionaryExtractor(vertex.getMetadataJson())); + break; + case PRODUCT: + metadata = new ProductMetadataData(new GraphPropertiesDictionaryExtractor(vertex.getMetadataJson())); + break; + default: + throw new StorageException(JanusGraphOperationStatus.INVALID_TYPE); } metadata.getMetadataDataDefinition().setUniqueId(vertex.getUniqueId()); metadata.getMetadataDataDefinition().setLastUpdateDate((Long) vertex.getJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE)); @@ -2017,42 +2088,44 @@ public class ModelConverter { List groupDefinitions = new ArrayList<>(); if (MapUtils.isNotEmpty(groups)) { - groupDefinitions = groups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); + groupDefinitions = groups.values().stream().map(GroupDefinition::new).collect(Collectors.toList()); } return groupDefinitions; - } - - public static Map extractCapabilityProperteisFromInstances(List instances, boolean fromCsar) { - return instances - .stream() - .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId, - ci -> convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), fromCsar))); - } - - public static Map extractCapabilityPropertiesFromGroups(List groups, boolean fromCsar) { - if(CollectionUtils.isNotEmpty(groups)) - return groups - .stream() - .collect(Collectors.toMap(GroupDefinition::getUniqueId, - g -> convertToMapOfMapCapabiltyProperties(g.getCapabilities(), g.getUniqueId(), fromCsar))); - return Maps.newHashMap(); - } - - public static Map extractCapabilitiesFromGroups(final List groupDefinitions) { - Map calculatedCapabilities = Maps.newHashMap(); - for(GroupDefinition groupDefinition :groupDefinitions){ - calculatedCapabilities.put(groupDefinition.getUniqueId(), new MapListCapabilityDataDefinition(buildMapOfListsOfCapabilities(groupDefinition))); - } - return calculatedCapabilities; - } - - private static Map buildMapOfListsOfCapabilities(GroupDefinition groupDefinition) { - return groupDefinition.getCapabilities().entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, e-> new ListCapabilityDataDefinition(e.getValue() - .stream() - .map(CapabilityDataDefinition::new) - .collect(Collectors.toList())))); + } + + public static Map extractCapabilityProperteisFromInstances(List instances, boolean fromCsar) { + return instances + .stream() + .collect(Collectors.toMap(ComponentInstanceDataDefinition::getUniqueId, + ci -> convertToMapOfMapCapabiltyProperties(ci.getCapabilities(), ci.getUniqueId(), fromCsar))); + } + + public static Map extractCapabilityPropertiesFromGroups(List groups, boolean fromCsar) { + if (CollectionUtils.isNotEmpty(groups)) { + return groups + .stream() + .collect(Collectors.toMap(GroupDefinition::getUniqueId, + g -> convertToMapOfMapCapabiltyProperties(g.getCapabilities(), g.getUniqueId(), fromCsar))); + } + return Maps.newHashMap(); + } + + public static Map extractCapabilitiesFromGroups(final List groupDefinitions) { + Map calculatedCapabilities = Maps.newHashMap(); + for (GroupDefinition groupDefinition : groupDefinitions) { + calculatedCapabilities + .put(groupDefinition.getUniqueId(), new MapListCapabilityDataDefinition(buildMapOfListsOfCapabilities(groupDefinition))); + } + return calculatedCapabilities; + } + + private static Map buildMapOfListsOfCapabilities(GroupDefinition groupDefinition) { + return groupDefinition.getCapabilities().entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> new ListCapabilityDataDefinition(e.getValue() + .stream() + .map(CapabilityDataDefinition::new) + .collect(Collectors.toList())))); } } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java index d499dfe799..1d1c8cd9dc 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java @@ -30,6 +30,7 @@ import org.openecomp.sdc.be.datatypes.elements.SubstitutionFilterDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; 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.ComponentInstance; import org.openecomp.sdc.be.model.ComponentInstanceAttribute; @@ -78,6 +79,7 @@ public class UiComponentDataTransfer { private Map nodeFilterforNode; private Map substitutionFilterForTopologyTemplate; private List properties; + private List attributes; private Map> componentInstancesInterfaces; public UiComponentDataTransfer() { diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java index a51c368c71..eabb2cde14 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiResourceDataTransfer.java @@ -25,7 +25,6 @@ import java.util.Map; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition; import org.openecomp.sdc.be.model.AttributeDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; @@ -43,7 +42,7 @@ public class UiResourceDataTransfer extends UiComponentDataTransfer { private List properties; - private List attributes; + private List attributes; private Map interfaces; diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentParametersViewTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentParametersViewTest.java index ec3604498b..1f6719531e 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentParametersViewTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ComponentParametersViewTest.java @@ -70,426 +70,6 @@ public class ComponentParametersViewTest { testSubject.disableAll(); } - - @Test - public void testIsIgnoreGroups() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreGroups(); - } - - - @Test - public void testSetIgnoreGroups() throws Exception { - ComponentParametersView testSubject; - boolean ignoreGroups = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreGroups(ignoreGroups); - } - - - @Test - public void testIsIgnoreComponentInstances() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreComponentInstances(); - } - - - @Test - public void testSetIgnoreComponentInstances() throws Exception { - ComponentParametersView testSubject; - boolean ignoreComponentInstances = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreComponentInstances(ignoreComponentInstances); - } - - - @Test - public void testIsIgnoreProperties() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreProperties(); - } - - - @Test - public void testSetIgnoreProperties() throws Exception { - ComponentParametersView testSubject; - boolean ignoreProperties = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreProperties(ignoreProperties); - } - - - @Test - public void testIsIgnoreCapabilities() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreCapabilities(); - } - - - @Test - public void testSetIgnoreCapabilities() throws Exception { - ComponentParametersView testSubject; - boolean ignoreCapabilities = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreCapabilities(ignoreCapabilities); - } - - - @Test - public void testIsIgnoreRequirements() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreRequirements(); - } - - - @Test - public void testSetIgnoreRequirements() throws Exception { - ComponentParametersView testSubject; - boolean ignoreRequirements = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreRequirements(ignoreRequirements); - } - - - @Test - public void testIsIgnoreCategories() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreCategories(); - } - - - @Test - public void testSetIgnoreCategories() throws Exception { - ComponentParametersView testSubject; - boolean ignoreCategories = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreCategories(ignoreCategories); - } - - - @Test - public void testIsIgnoreAllVersions() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreAllVersions(); - } - - - @Test - public void testSetIgnoreAllVersions() throws Exception { - ComponentParametersView testSubject; - boolean ignoreAllVersions = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreAllVersions(ignoreAllVersions); - } - - - @Test - public void testIsIgnoreAdditionalInformation() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreAdditionalInformation(); - } - - - @Test - public void testIsIgnoreArtifacts() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreArtifacts(); - } - - - @Test - public void testSetIgnoreArtifacts() throws Exception { - ComponentParametersView testSubject; - boolean ignoreArtifacts = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreArtifacts(ignoreArtifacts); - } - - - @Test - public void testIsIgnoreComponentInstancesProperties() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreComponentInstancesProperties(); - } - - - @Test - public void testSetIgnoreComponentInstancesProperties() throws Exception { - ComponentParametersView testSubject; - boolean ignoreComponentInstancesProperties = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreComponentInstancesProperties(ignoreComponentInstancesProperties); - } - - - @Test - public void testIsIgnoreComponentInstancesInputs() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreComponentInstancesInputs(); - } - - - @Test - public void testSetIgnoreComponentInstancesInputs() throws Exception { - ComponentParametersView testSubject; - boolean ignoreComponentInstancesInputs = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreComponentInstancesInputs(ignoreComponentInstancesInputs); - } - - - @Test - public void testIsIgnoreInterfaces() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreInterfaces(); - } - - - - @Test - public void testIsIgnoreAttributesFrom() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreAttributesFrom(); - } - - - @Test - public void testSetIgnoreAttributesFrom() throws Exception { - ComponentParametersView testSubject; - boolean ignoreAttributesFrom = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreAttributesFrom(ignoreAttributesFrom); - } - - - @Test - public void testIsIgnoreComponentInstancesAttributesFrom() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreComponentInstancesAttributesFrom(); - } - - - - @Test - public void testIsIgnoreDerivedFrom() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreDerivedFrom(); - } - - - - @Test - public void testIsIgnoreUsers() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreUsers(); - } - - - @Test - public void testSetIgnoreUsers() throws Exception { - ComponentParametersView testSubject; - boolean ignoreUsers = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreUsers(ignoreUsers); - } - - - @Test - public void testIsIgnoreInputs() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreInputs(); - } - - - @Test - public void testSetIgnoreInputs() throws Exception { - ComponentParametersView testSubject; - boolean ignoreInputs = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreInputs(ignoreInputs); - } - - - @Test - public void testIsIgnoreCapabiltyProperties() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreCapabiltyProperties(); - } - - - @Test - public void testSetIgnoreCapabiltyProperties() throws Exception { - ComponentParametersView testSubject; - boolean ignoreCapabiltyProperties = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreCapabiltyProperties(ignoreCapabiltyProperties); - } - - - @Test - public void testIsIgnoreForwardingPath() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnoreForwardingPath(); - } - - - @Test - public void testSetIgnoreForwardingPath() throws Exception { - ComponentParametersView testSubject; - boolean ignoreServicePath = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnoreForwardingPath(ignoreServicePath); - } - - - @Test - public void testIsIgnorePolicies() throws Exception { - ComponentParametersView testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isIgnorePolicies(); - } - - - @Test - public void testSetIgnorePolicies() throws Exception { - ComponentParametersView testSubject; - boolean ignorePolicies = false; - - // default test - testSubject = createTestSubject(); - testSubject.setIgnorePolicies(ignorePolicies); - } - - - @Test - public void testIsIgnoreNodeFilterWithTrue() throws Exception { - ComponentParametersView testSubject; - - testSubject = createTestSubject(); - testSubject.setIgnoreNodeFilter(true); - assertSame(testSubject.isIgnoreNodeFilter(), true); - } - - - @Test - public void testIsIgnoreNodeFilterWithFalse() throws Exception { - ComponentParametersView testSubject; - - testSubject = createTestSubject(); - testSubject.setIgnoreNodeFilter(false); - assertSame(testSubject.isIgnoreNodeFilter(), false); - } - - @Test public void testDetectParseFlag() throws Exception { ComponentParametersView testSubject; diff --git a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java index 6b9ef75b61..cb22394463 100644 --- a/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java +++ b/common-app-logging/src/main/java/org/openecomp/sdc/common/log/elements/LoggerSupportability.java @@ -51,6 +51,10 @@ public class LoggerSupportability extends LoggerBase { logger); } + public static LoggerSupportability getLogger(Class clazz) { + return LoggerFactory.getMdcLogger(LoggerSupportability.class, org.slf4j.LoggerFactory.getLogger(clazz)); + } + public static LoggerSupportability getLogger(String className) { return LoggerFactory.getMdcLogger(LoggerSupportability.class, org.slf4j.LoggerFactory.getLogger(className)); diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java index 27bd6635fb..f1ca2167f6 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/AttributeDataDefinition.java @@ -20,12 +20,21 @@ package org.openecomp.sdc.be.datatypes.elements; import java.io.Serializable; +import java.util.List; +import lombok.Getter; +import lombok.Setter; import org.onap.sdc.tosca.datatypes.model.EntrySchema; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +@Getter +@Setter public class AttributeDataDefinition extends ToscaDataDefinition implements Serializable { + private List getOutputValues; + private String outputId; + private String value; + public AttributeDataDefinition() { } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetOutputValueDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetOutputValueDataDefinition.java new file mode 100644 index 0000000000..8bb7f7e153 --- /dev/null +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/GetOutputValueDataDefinition.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2021, Nordix Foundation. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.datatypes.elements; + +import java.util.Map; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; + +@Getter +@Setter +@EqualsAndHashCode +@ToString +public class GetOutputValueDataDefinition extends ToscaDataDefinition { + + private String attribName; + private String inputName; + private String inputId; + private Integer indexValue; + private GetOutputValueDataDefinition getOutputIndex; + private boolean isList = false; + + public GetOutputValueDataDefinition() { + super(); + } + + public GetOutputValueDataDefinition(Map pr) { + super(pr); + } + + public GetOutputValueDataDefinition(GetOutputValueDataDefinition p) { + this.setAttribName(p.getAttribName()); + this.setInputName(p.getInputName()); + this.setInputId(p.getInputId()); + this.setIndexValue(p.getIndexValue()); + this.setGetOutputIndex(p.getGetOutputIndex()); + this.setList(p.isList()); + } + +} diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java index 643c03fbe1..91c956d613 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/ComponentFieldsEnum.java @@ -24,6 +24,7 @@ public enum ComponentFieldsEnum { PROPERTIES("properties"), INPUTS("inputs"), + OUTPUTS("outputs"), USERS("users"), GROUPS("groups"), NON_EXCLUDED_GROUPS("nonExcludedGroups"), diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/pom.xml index 1c4e4f9d13..f3746ccbff 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/pom.xml @@ -20,13 +20,11 @@ openecomp-nosqldb-api openecomp-nosqldb-api - org.openecomp.sdc.core - openecomp-sdc-lib - org.openecomp.sdc + openecomp-nosqldb-lib + org.openecomp.sdc.core 1.8.1-SNAPSHOT - ../../.. diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/pom.xml index 7d8a626515..8d5c7c2d89 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/pom.xml @@ -21,16 +21,13 @@ openecomp-nosqldb-core openecomp-nosqldb-core - org.openecomp.sdc.core - openecomp-sdc-lib - org.openecomp.sdc + openecomp-nosqldb-lib + org.openecomp.sdc.core 1.8.1-SNAPSHOT - ../../.. - org.onap.sdc.common @@ -39,13 +36,14 @@ org.openecomp.sdc.core - openecomp-nosqldb-api + openecomp-session-lib ${project.version} org.openecomp.sdc.core - openecomp-session-lib + openecomp-nosqldb-api ${project.version} + compile diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/pom.xml index 4b0d552236..3a48db6c92 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/pom.xml @@ -4,13 +4,12 @@ openecomp-nosqldb-lib openecomp-nosqldb-lib - org.openecomp.sdc.core + pom - openecomp-sdc-lib - org.openecomp.sdc + openecomp-core-lib + org.openecomp.sdc.core 1.8.1-SNAPSHOT - ../.. @@ -18,18 +17,4 @@ openecomp-nosqldb-core - - - org.openecomp.sdc.core - openecomp-nosqldb-api - ${project.version} - compile - - - org.openecomp.sdc.core - openecomp-nosqldb-core - ${project.version} - runtime - - \ No newline at end of file -- cgit 1.2.3-korg