diff options
Diffstat (limited to 'catalog-be/src/main/java/org')
23 files changed, 1198 insertions, 318 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java index 65f1e4981a..49dd3d6c01 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/BaseBusinessLogic.java @@ -21,17 +21,15 @@ package org.openecomp.sdc.be.components.impl; import com.google.gson.JsonElement; - +import fj.data.Either; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; - -import fj.data.Either; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.components.validation.UserValidations; @@ -46,8 +44,10 @@ import org.openecomp.sdc.be.datatypes.elements.PropertyRule; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.IComplexDefaultValue; @@ -95,6 +95,7 @@ public abstract class BaseBusinessLogic { private static final String SCHEMA_DOESN_T_EXISTS_FOR_PROPERTY_OF_TYPE = "Schema doesn't exists for property of type {}"; private static final String PROPERTY_IN_SCHEMA_DEFINITION_INSIDE_PROPERTY_OF_TYPE_DOESN_T_EXIST = "Property in Schema Definition inside property of type {} doesn't exist"; private static final String ADD_PROPERTY_VALUE = "Add property value"; + private static final String THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID = "The value {} of property from type {} is invalid"; @Autowired protected ComponentsUtils componentsUtils; @@ -147,6 +148,9 @@ public abstract class BaseBusinessLogic { protected InterfaceOperation interfaceOperation; @Autowired + protected InterfaceOperationBusinessLogic interfaceOperationBusinessLogic; + + @Autowired protected InterfaceLifecycleOperation interfaceLifecycleTypeOperation; @javax.annotation.Resource @@ -175,6 +179,10 @@ public abstract class BaseBusinessLogic { this.toscaOperationFacade = toscaOperationFacade; } + public void setPolicyTypeOperation(PolicyTypeOperation policyTypeOperation) { + this.policyTypeOperation = policyTypeOperation; + } + public void setDataTypeCache(ApplicationDataTypeCache dataTypeCache) { this.dataTypeCache = dataTypeCache; } @@ -183,6 +191,14 @@ public abstract class BaseBusinessLogic { this.propertyOperation = propertyOperation; } + public void setInterfaceOperation(InterfaceOperation interfaceOperation) { + this.interfaceOperation = interfaceOperation; + } + public void setInterfaceOperationBusinessLogic(InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) { + this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic; + } + + User validateUserNotEmpty(User user, String ecompErrorContext) { return userValidations.validateUserNotEmpty(user, ecompErrorContext); } @@ -191,10 +207,15 @@ public abstract class BaseBusinessLogic { return userValidations.validateUserExists(user.getUserId(), ecompErrorContext, inTransaction); } - void validateUserExist(String userId, String ecompErrorContext) { - userValidations.validateUserExist(userId, ecompErrorContext); + protected void validateUserExist(String userId, String ecompErrorContext) { + userValidations.validateUserExist(userId, ecompErrorContext); } + public void setGroupTypeOperation(IGroupTypeOperation groupTypeOperation) { + this.groupTypeOperation = groupTypeOperation; + } + + Either<User, ActionStatus> validateUserExistsActionStatus(String userId, String ecompErrorContext) { return userValidations.validateUserExistsActionStatus(userId, ecompErrorContext); } @@ -326,7 +347,9 @@ public abstract class BaseBusinessLogic { String propertyType = property.getType(); String innerType = getInnerType(property); // Specific Update Logic - Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes); + Either<Object, Boolean> isValid = + propertyOperation.validateAndUpdatePropertyValue(propertyType, (String) property.getValue(), true, + innerType, allDataTypes); String newValue = property.getValue(); if (isValid.isRight()) { Boolean res = isValid.right().value(); @@ -436,7 +459,7 @@ public abstract class BaseBusinessLogic { ImmutablePair<String, Boolean> propertyInnerTypeValid = propertyOperation.isPropertyInnerTypeValid(property, dataTypes); innerType = propertyInnerTypeValid.getLeft(); if (!propertyInnerTypeValid.getRight()) { - log.info("Invalid inner type for property {} type {}", property.getName(), property.getType()); + log.info("Invalid inner type for property {} type {}, dataTypeCount {}", property.getName(), property.getType(), dataTypes.size()); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_PROPERTY_INNER_TYPE, innerType, property.getName()); return Either.right(responseFormat); } @@ -445,9 +468,11 @@ public abstract class BaseBusinessLogic { log.info("Invalid default value for property {} type {}", property.getName(), property.getType()); ResponseFormat responseFormat; if (type.equals(ToscaPropertyType.LIST.getType()) || type.equals(ToscaPropertyType.MAP.getType())) { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, property.getDefaultValue()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_COMPLEX_DEFAULT_VALUE, property.getName(), type, innerType, + property.getDefaultValue()); } else { - responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, property.getDefaultValue()); + responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEFAULT_VALUE, property.getName(), type, + property.getDefaultValue()); } return Either.right(responseFormat); @@ -611,7 +636,7 @@ public abstract class BaseBusinessLogic { DataTypeDefinition dataTypeDefinition = dataTypes.get(propertyType); ImmutablePair<JsonElement, Boolean> validateResult = dataTypeValidatorConverter.validateAndUpdate(value, dataTypeDefinition, dataTypes); if (Boolean.FALSE.equals(validateResult.right)) { - log.debug("The value {} of property from type {} is invalid", value, propertyType); + log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, propertyType); return Either.right(false); } JsonElement jsonElement = validateResult.left; @@ -621,7 +646,7 @@ public abstract class BaseBusinessLogic { log.trace("before validating property type {}", propertyType); boolean isValidProperty = isValidValue(type, value, innerType, dataTypes); if (!isValidProperty) { - log.debug("The value {} of property from type {} is invalid", value, type); + log.debug(THE_VALUE_OF_PROPERTY_FROM_TYPE_IS_INVALID, value, type); return Either.right(false); } } @@ -683,64 +708,70 @@ public abstract class BaseBusinessLogic { } return jsonElement.toString(); } - - void rollbackWithException(ActionStatus actionStatus, String... params) { + + protected void rollbackWithException(ActionStatus actionStatus, String... params) { titanDao.rollback(); throw new ComponentException(actionStatus, params); } - public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) { - if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) - && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) { - return setConstraint(inputDefinition); - } - - return Collections.emptyList(); - } - - private <T extends PropertyDataDefinition> List<PropertyConstraint> setConstraint(T inputDefinition) { - List<PropertyConstraint> constraints = new ArrayList<>(); - String[] inputPathArr = inputDefinition.getSubPropertyInputPath().split("#"); - if (inputPathArr.length > 1) { - inputPathArr = ArrayUtils.remove(inputPathArr, 0); - } - - Map<String, DataTypeDefinition> dataTypeDefinitionMap = - applicationDataTypeCache.getAll().left().value(); - - String propertyType = inputDefinition.getParentPropertyType(); - - for (String anInputPathArr : inputPathArr) { - if (ToscaType.isPrimitiveType(propertyType)) { - constraints.addAll( - dataTypeDefinitionMap.get(propertyType).getConstraints()); - } else if (!ToscaType.isCollectionType(propertyType)) { - propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr, - constraints); - } - } - - return constraints; - } - - private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap, - String propertyType, - String anInputPathArr, - List<PropertyConstraint> constraints) { - String type = null; - List<PropertyDefinition> propertyDefinitions = - dataTypeDefinitionMap.get(propertyType).getProperties(); - for (PropertyDefinition propertyDefinition : propertyDefinitions) { - if (propertyDefinition.getName().equals(anInputPathArr)) { - if (ToscaType.isPrimitiveType(propertyDefinition.getType())) { - constraints.addAll(propertyDefinition.getConstraints()); - } else { - type = propertyDefinition.getType(); - } - break; - } - } - - return type; - } + public <T extends ToscaDataDefinition> Either<List<T>, ResponseFormat> declareProperties(String userId, String componentId, + ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) { + + return Either.left(new ArrayList<>()); + } + + public <T extends PropertyDataDefinition> List<PropertyConstraint> setInputConstraint(T inputDefinition) { + if (StringUtils.isNotBlank(inputDefinition.getParentPropertyType()) + && StringUtils.isNotBlank(inputDefinition.getSubPropertyInputPath())) { + return setConstraint(inputDefinition); + } + + return Collections.emptyList(); + } + + private <T extends PropertyDataDefinition> List<PropertyConstraint> setConstraint(T inputDefinition) { + List<PropertyConstraint> constraints = new ArrayList<>(); + String[] inputPathArr = inputDefinition.getSubPropertyInputPath().split("#"); + if (inputPathArr.length > 1) { + inputPathArr = ArrayUtils.remove(inputPathArr, 0); + } + + Map<String, DataTypeDefinition> dataTypeDefinitionMap = + applicationDataTypeCache.getAll().left().value(); + + String propertyType = inputDefinition.getParentPropertyType(); + + for (String anInputPathArr : inputPathArr) { + if (ToscaType.isPrimitiveType(propertyType)) { + constraints.addAll( + dataTypeDefinitionMap.get(propertyType).getConstraints()); + } else if (!ToscaType.isCollectionType(propertyType)) { + propertyType = setConstraintForComplexType(dataTypeDefinitionMap, propertyType, anInputPathArr, + constraints); + } + } + + return constraints; + } + + private String setConstraintForComplexType(Map<String, DataTypeDefinition> dataTypeDefinitionMap, + String propertyType, + String anInputPathArr, + List<PropertyConstraint> constraints) { + String type = null; + List<PropertyDefinition> propertyDefinitions = + dataTypeDefinitionMap.get(propertyType).getProperties(); + for (PropertyDefinition propertyDefinition : propertyDefinitions) { + if (propertyDefinition.getName().equals(anInputPathArr)) { + if (ToscaType.isPrimitiveType(propertyDefinition.getType())) { + constraints.addAll(propertyDefinition.getConstraints()); + } else { + type = propertyDefinition.getType(); + } + break; + } + } + + return type; + } } 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 0c6735f8c1..3bae240a67 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 @@ -62,6 +62,7 @@ import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition; @@ -93,7 +94,23 @@ import org.openecomp.sdc.be.model.RequirementDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +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.PolicyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition.PropertyNames; +import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; +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.PropertyDefinition.PropertyNames; import org.openecomp.sdc.be.model.jsontitan.operations.ForwardingPathOperation; import org.openecomp.sdc.be.model.jsontitan.operations.NodeFilterOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; @@ -134,9 +151,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { public static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas"; public static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK"; - @Autowired - private ApplicationDataTypeCache applicationDataTypeCache; - @Autowired private IComponentInstanceOperation componentInstanceOperation; @@ -158,9 +172,10 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { public ComponentInstanceBusinessLogic() { } - public Either<ComponentInstance, ResponseFormat> createComponentInstance( - String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) { - return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true); + public Either<ComponentInstance, ResponseFormat> createComponentInstance(String containerComponentParam, + String containerComponentId, String userId, ComponentInstance resourceInstance) { + return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, + true); } public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ @@ -196,7 +211,69 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return resList; } - public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId){ + public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component, + PolicyDefinition policy) { + + Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy); + + if(propertyCandidate.isPresent()) { + ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get(); + Optional<GetPolicyValueDataDefinition> getPolicyCandidate = + getGetPolicyValueDataDefinition(policy, componentInstanceProperty); + + getPolicyCandidate.ifPresent(getPolicyValue -> + updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy)); + return Optional.of(componentInstanceProperty); + } + + return Optional.empty(); + + } + + private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty, + GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) { + componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue()); + List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues(); + if(CollectionUtils.isNotEmpty(getPolicyValues)) { + getPolicyValues.remove(getPolicyValue); + componentInstanceProperty.setGetPolicyValues(getPolicyValues); + policyDefinition.setGetPolicyValues(getPolicyValues); + } + } + + private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy, + ComponentInstanceProperty componentInstanceProperty) { + List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues(); + return getPolicyValues.stream() + .filter(getPolicyValue -> getPolicyValue + .getPropertyName() + .equals(componentInstanceProperty + .getName())) + .findAny(); + } + + private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component, + PolicyDefinition policy) { + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = + component.getComponentInstancesProperties(); + + if(MapUtils.isEmpty(componentInstancesProperties)) { + return Optional.empty(); + } + + String instanceUniqueId = policy.getInstanceUniqueId(); + + List<ComponentInstanceProperty> componentInstanceProperties = + componentInstancesProperties.containsKey(instanceUniqueId) + ? componentInstancesProperties.get(instanceUniqueId) + : new ArrayList<>(); + + return componentInstanceProperties + .stream().filter(property -> property.getName().equals(policy.getName())).findAny(); + } + + public List<ComponentInstanceInput> getComponentInstanceInputsByInputId( + org.openecomp.sdc.be.model.Component component, String inputId) { List<ComponentInstanceInput> resList = new ArrayList<>(); Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs(); if(ciInputsMap != null && !ciInputsMap.isEmpty()){ diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java index f3b1b14652..214b5df4e1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogic.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.be.components.impl; +import fj.data.Either; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -27,9 +28,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; - -import fj.data.Either; -import org.apache.commons.collections4.CollectionUtils; +import javax.inject.Inject; import org.apache.commons.collections4.ListUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator; @@ -49,19 +48,14 @@ 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.InputDefinition; -import org.openecomp.sdc.be.model.PropertyDefinition; -import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; 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; -import javax.inject.Inject; - @Component("inputsBusinessLogic") public class InputsBusinessLogic extends BaseBusinessLogic { @@ -399,6 +393,13 @@ public class InputsBusinessLogic extends BaseBusinessLogic { } + @Override + public Either<List<InputDefinition>, ResponseFormat> declareProperties(String userId, String componentId, + ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) { + + return createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); + } + public Either<List<InputDefinition>, ResponseFormat> createMultipleInputs(String userId, String componentId, ComponentTypeEnum componentType, ComponentInstInputsMap componentInstInputsMapUi, boolean shouldLockComp, boolean inTransaction) { Either<List<InputDefinition>, ResponseFormat> result = null; @@ -544,6 +545,8 @@ public class InputsBusinessLogic extends BaseBusinessLogic { componentParametersView.setIgnorePolicies(false); componentParametersView.setIgnoreGroups(false); componentParametersView.setIgnoreUsers(false); + componentParametersView.setIgnoreInterfaces(false); + componentParametersView.setIgnoreProperties(false); Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentEither = toscaOperationFacade.getToscaElement(componentId, componentParametersView); if (componentEither.isRight()) { @@ -614,17 +617,19 @@ public class InputsBusinessLogic extends BaseBusinessLogic { PropertyValueConverter converter = type.getConverter(); // get inner type String innerType = null; - SchemaDefinition schema = newInputDefinition.getSchema(); - if (schema != null) { - PropertyDataDefinition prop = schema.getProperty(); - if (prop != null) { - innerType = prop.getType(); + if (newInputDefinition != null) { + SchemaDefinition schema = newInputDefinition.getSchema(); + if (schema != null) { + PropertyDataDefinition prop = schema.getProperty(); + if (prop != null) { + innerType = prop.getType(); + } + } + String convertedValue; + if (newInputDefinition.getDefaultValue() != null) { + convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes); + newInputDefinition.setDefaultValue(convertedValue); } - } - String convertedValue; - if (newInputDefinition.getDefaultValue() != null) { - convertedValue = converter.convert(newInputDefinition.getDefaultValue(), innerType, dataTypes); - newInputDefinition.setDefaultValue(convertedValue); } } return Either.left(newInputDefinition); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java index 6b37318171..752ec4098a 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/PolicyBusinessLogic.java @@ -1,28 +1,42 @@ package org.openecomp.sdc.be.components.impl; +import static java.util.stream.Collectors.toMap; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.getExcludedPolicyTypesByComponent; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.getNextPolicyCounter; +import static org.openecomp.sdc.be.components.validation.PolicyUtils.validatePolicyFields; + import fj.data.Either; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; +import javax.inject.Inject; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.components.property.PropertyDeclarationOrchestrator; +import org.openecomp.sdc.be.components.validation.PolicyUtils; import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PolicyTypeDefinition; +import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static java.util.stream.Collectors.toMap; -import static org.openecomp.sdc.be.components.validation.PolicyUtils.*; - /** * Provides specified business logic to create, retrieve, update, delete a policy */ @@ -30,8 +44,25 @@ import static org.openecomp.sdc.be.components.validation.PolicyUtils.*; public class PolicyBusinessLogic extends BaseBusinessLogic { private static final String FAILED_TO_VALIDATE_COMPONENT = "#{} - failed to validate the component {} before policy processing. "; + private static final String DECLARE_PROPERTIES_TO_POLICIES = "declare properties to policies"; + private static final String EXECUTE_ROLLBACK = "execute rollback"; + private static final String EXECUTE_COMMIT = "execute commit"; private static final Logger log = Logger.getLogger(PolicyBusinessLogic.class); + @Inject + private PropertyDeclarationOrchestrator propertyDeclarationOrchestrator; + + public PolicyBusinessLogic() { + } + + public PolicyBusinessLogic(PropertyDeclarationOrchestrator propertyDeclarationOrchestrator) { + this.propertyDeclarationOrchestrator = propertyDeclarationOrchestrator; + } + + public void setPropertyDeclarationOrchestrator(PropertyDeclarationOrchestrator propertyDeclarationOrchestrator) { + this.propertyDeclarationOrchestrator = propertyDeclarationOrchestrator; + } + /** * Adds the newly created policy of the specified type to the component * @@ -65,6 +96,20 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return result; } + public Either<List<PolicyDefinition>, ResponseFormat> getPoliciesList(ComponentTypeEnum componentType, String componentId, String userId) { + Either<List<PolicyDefinition>, ResponseFormat> result; + log.trace("#getPolicies - starting to retrieve policies of component {}. ", componentId); + try { + result = validateContainerComponentAndUserBeforeReadOperation(componentType, componentId, userId) + .left() + .bind(c -> Either.left(c.resolvePoliciesList())); + } catch (Exception e) { + log.error("#getPolicy - the exception occurred upon retrieving policies list of component {}: ", componentId, e); + result = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + return result; + } + /** * Retrieves the policy of the component by UniqueId * @@ -133,18 +178,138 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { log.trace("#deletePolicy - starting to update the policy {} on the component {}. ", policyId, componentId); Wrapper<Component> component = new Wrapper<>(); try { - result = validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock) - .left() - .bind(c -> { - component.setInnerElement(c); - return deletePolicy(c, policyId); - }); + Either<Component, ResponseFormat> componentEither = + validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); + if (componentEither.isRight()) { + return Either.right(componentEither.right().value()); + } + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); + componentParametersView.setIgnorePolicies(false); + componentParametersView.setIgnoreProperties(false); + + Either<Component, StorageOperationStatus> componentWithFilters = + toscaOperationFacade.getToscaElement(componentId, componentParametersView); + if (componentWithFilters.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentWithFilters.right().value()))); + } + + Component containerComponent = componentWithFilters.left().value(); + component.setInnerElement(containerComponent); + result = deletePolicy(containerComponent, policyId); + + if(result.isRight()) { + log.error("#deletePolicy - could not delete policy of the type {} for the component {}: ", policyId, componentId); + return result; + } + + PolicyDefinition policyToDelete = result.left().value(); + + StorageOperationStatus storageOperationStatus = propertyDeclarationOrchestrator.unDeclarePropertiesAsPolicies( + containerComponent, policyToDelete); + if (storageOperationStatus != StorageOperationStatus.OK) { + log.debug("Component id: {} update properties declared as policy for policy id: {} failed", componentId, policyId); + return Either.right(componentsUtils.getResponseFormat(componentsUtils + .convertFromStorageResponse(storageOperationStatus), containerComponent.getName())); + } + + return result; } catch (Exception e) { log.error("#deletePolicy - the exception occurred upon update of a policy of the type {} for the component {}: ", policyId, componentId, e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, e.getMessage())); + } finally { + unlockComponent(shouldLock, result, component); + } + } + + public Either<PolicyDefinition, ResponseFormat> undeclarePolicy(ComponentTypeEnum componentType, String componentId, String policyId, String userId, boolean shouldLock) { + Either<PolicyDefinition, ResponseFormat> result = null; + log.trace("#undeclarePolicy - starting to undeclare policy {} on component {}. ", policyId, componentId); + Wrapper<Component> component = new Wrapper<>(); + try { + Either<Component, ResponseFormat> componentEither = + validateAndLockComponentAndUserBeforeWriteOperation(componentType, componentId, userId, shouldLock); + if (componentEither.isRight()) { + return Either.right(componentEither.right().value()); + } + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); + componentParametersView.setIgnorePolicies(false); + + Either<Component, StorageOperationStatus> componentWithFilters = + toscaOperationFacade.getToscaElement(componentId, componentParametersView); + if (componentWithFilters.isRight()) { + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(componentWithFilters.right().value()))); + } + + Component containerComponent = componentWithFilters.left().value(); + + Optional<PolicyDefinition> policyCandidate = getPolicyForUndeclaration(policyId, containerComponent); + if(policyCandidate.isPresent()) { + result = undeclarePolicy(policyCandidate.get(), containerComponent); + } + + return result; + } catch (Exception e) { + log.error("#undeclarePolicy - the exception occurred upon update of a policy of type {} for component {}: ", policyId, componentId, e); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR, e.getMessage())); } finally { unlockComponent(shouldLock, result, component); } - return result; + } + + + private Either<PolicyDefinition, ResponseFormat> undeclarePolicy(PolicyDefinition policyDefinition, Component containerComponent) { + StorageOperationStatus undeclareStatus = propertyDeclarationOrchestrator + .unDeclarePropertiesAsPolicies(containerComponent, policyDefinition); + if(undeclareStatus != StorageOperationStatus.OK){ + return Either.right(componentsUtils.getResponseFormat(undeclareStatus)); + } else { + return Either.left(policyDefinition); + } + } + + + private Optional<PolicyDefinition> getPolicyForUndeclaration(String policyId, Component component) { + Map<String, PolicyDefinition> policies = component.getPolicies(); + if(MapUtils.isNotEmpty(policies) && policies.containsKey(policyId)) { + return Optional.of(policies.get(policyId)); + } + + Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = + MapUtils.isEmpty(component.getComponentInstancesProperties()) ? new HashMap<>() : component.getComponentInstancesProperties(); + + for(Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstancesProperties.entrySet()) { + Optional<ComponentInstanceProperty> propertyCandidate = getPropertyForDeclaredPolicy(policyId, instancePropertyEntry.getValue()); + + if(propertyCandidate.isPresent()) { + return Optional.of( + PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), propertyCandidate.get())); + } + } + + return Optional.empty(); + } + + private Optional<ComponentInstanceProperty> getPropertyForDeclaredPolicy(String policyId, List<ComponentInstanceProperty> componentInstanceProperties) { + for(ComponentInstanceProperty property : componentInstanceProperties) { + Optional<GetPolicyValueDataDefinition> getPolicyCandidate = property.safeGetGetPolicyValues().stream() + .filter(getPolicyValue -> getPolicyValue.getPolicyId() + .equals(policyId)) + .findAny(); + + if(getPolicyCandidate.isPresent()) { + return Optional.of(property); + } + } + + return Optional.empty(); } public Either<PolicyDefinition, ResponseFormat> updatePolicyTargets(ComponentTypeEnum componentTypeEnum, String componentId, String policyId, Map<PolicyTargetType, List<String>> targets, String userId) { @@ -266,6 +431,71 @@ public class PolicyBusinessLogic extends BaseBusinessLogic { return result; } + @Override + public Either<List<PolicyDefinition>, ResponseFormat> declareProperties(String userId, String componentId, + ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap) { + return declarePropertiesToPolicies(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); + + } + + private Either<List<PolicyDefinition>, ResponseFormat> declarePropertiesToPolicies(String userId, String componentId, + ComponentTypeEnum componentTypeEnum, ComponentInstInputsMap componentInstInputsMap, boolean shouldLock, + boolean inTransaction) { + Either<List<PolicyDefinition>, ResponseFormat> result = null; + org.openecomp.sdc.be.model.Component component = null; + + try { + validateUserExists(userId, DECLARE_PROPERTIES_TO_POLICIES, false); + + ComponentParametersView componentParametersView = new ComponentParametersView(); + componentParametersView.disableAll(); + componentParametersView.setIgnoreComponentInstances(false); + componentParametersView.setIgnoreComponentInstancesProperties(false); + componentParametersView.setIgnorePolicies(false); + componentParametersView.setIgnoreUsers(false); + + Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(componentId, componentTypeEnum, componentParametersView); + + if (validateComponent.isRight()) { + result = Either.right(validateComponent.right().value()); + return result; + } + component = validateComponent.left().value(); + + if (shouldLock) { + Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, DECLARE_PROPERTIES_TO_POLICIES); + if (lockComponent.isRight()) { + result = Either.right(lockComponent.right().value()); + return result; + } + } + + Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId); + if (canWork.isRight()) { + result = Either.right(canWork.right().value()); + return result; + } + + Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesEither = + propertyDeclarationOrchestrator.declarePropertiesToPolicies(component, componentInstInputsMap); + + if(declarePropertiesEither.isRight()) { + return Either.right(componentsUtils.getResponseFormat(declarePropertiesEither.right().value())); + } + + result = Either.left(declarePropertiesEither.left().value()); + return result; + } finally { + if(!inTransaction) { + commitOrRollback(result); + } + // unlock resource + if (shouldLock && component != null) { + graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType()); + } + } + } + private Either<List<PropertyDataDefinition>, ResponseFormat> setComponentValidateUpdatePolicyProperties(String policyId, PropertyDataDefinition[] properties, Wrapper<Component> component, Component c) { component.setInnerElement(c); Set<String> updatedPropertyNames = Arrays.stream(properties).map(PropertyDataDefinition::getName).collect(Collectors.toSet()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java index 83d6730534..d1bfcc8bba 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ServiceBusinessLogic.java @@ -475,14 +475,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { ServiceConsumptionSource sourceValue = ServiceConsumptionSource.getSourceValue(source); if(STATIC.equals(sourceValue)) { - // Validate constraint on input value - /*Either<Boolean, ResponseFormat> constraintValidationResult = - validateOperationInputConstraint(operationInputDefinition, serviceConsumptionData); - - if (constraintValidationResult.isRight()) { - return Either.right(constraintValidationResult.right().value()); - }*/ - return handleConsumptionStaticValue(consumptionValue, type, operation, operationInputDefinition); } @@ -958,10 +950,10 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { service.setInvariantUUID(invariantUUID); return Either.left(service); - } - - - + } + + + private Either<Boolean, ResponseFormat> validateServiceFieldsBeforeCreate(User user, Service service, AuditingActionEnum actionEnum) { try { validateComponentFieldsBeforeCreate(user, service, actionEnum); @@ -1547,7 +1539,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { } return Either.left(true); } - + private Either<Boolean, ResponseFormat> validateServiceRole(String serviceRole) { if (serviceRole.equals("")){ return Either.left(true); @@ -2636,6 +2628,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { public Either<UiComponentDataTransfer, ResponseFormat> getUiComponentDataTransferByComponentId(String serviceId, List<String> dataParamsToReturn) { ComponentParametersView paramsToReturn = new ComponentParametersView(dataParamsToReturn); + paramsToReturn.setIgnoreComponentInstancesProperties(false); Either<Service, StorageOperationStatus> serviceResultEither = toscaOperationFacade.getToscaElement(serviceId, paramsToReturn); if (serviceResultEither.isRight()) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java index 9bf462a186..faeca88d60 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstanceInputPropertyDeclarator.java @@ -1,22 +1,30 @@ package org.openecomp.sdc.be.components.property; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getInputAnnotations; + import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.components.impl.utils.ExceptionUtils; import org.openecomp.sdc.be.datatypes.elements.Annotation; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.*; +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.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.ComponentParametersView; +import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.*; - -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.openecomp.sdc.be.model.utils.ComponentUtilities.getInputAnnotations; - @org.springframework.stereotype.Component public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDeclarator<ComponentInstance, ComponentInstanceInput> { @@ -33,25 +41,25 @@ public class ComponentInstanceInputPropertyDeclarator extends DefaultPropertyDec } @Override - ComponentInstanceInput createDeclaredProperty(PropertyDataDefinition prop) { + public ComponentInstanceInput createDeclaredProperty(PropertyDataDefinition prop) { return new ComponentInstanceInput(prop); } @Override - Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceInput> properties) { + public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceInput> properties) { log.debug("#updatePropertiesValues - updating component instance inputs for instance {} on component {}", cmptInstanceId, component.getUniqueId()); Map<String, List<ComponentInstanceInput>> instProperties = Collections.singletonMap(cmptInstanceId, properties); return toscaOperationFacade.addComponentInstanceInputsToComponent(component, instProperties); } @Override - Optional<ComponentInstance> resolvePropertiesOwner(Component component, String propertiesOwnerId) { + public Optional<ComponentInstance> resolvePropertiesOwner(Component component, String propertiesOwnerId) { log.debug("#resolvePropertiesOwner - fetching component instance {} of component {}", propertiesOwnerId, component.getUniqueId()); return component.getComponentInstanceById(propertiesOwnerId); } @Override - void addPropertiesListToInput(ComponentInstanceInput declaredProp, InputDefinition input) { + public void addPropertiesListToInput(ComponentInstanceInput declaredProp, InputDefinition input) { List<ComponentInstanceInput> inputsValueList = input.getInputs(); if(inputsValueList == null) { inputsValueList = new ArrayList<>(); // adding the property with the new value for UI diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java index 160bf890b7..c716e24440 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentInstancePropertyDeclarator.java @@ -1,6 +1,11 @@ package org.openecomp.sdc.be.components.property; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -14,8 +19,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.*; - @org.springframework.stereotype.Component public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarator<ComponentInstance, ComponentInstanceProperty> { @@ -30,25 +33,25 @@ public class ComponentInstancePropertyDeclarator extends DefaultPropertyDeclarat } @Override - ComponentInstanceProperty createDeclaredProperty(PropertyDataDefinition prop) { + public ComponentInstanceProperty createDeclaredProperty(PropertyDataDefinition prop) { return new ComponentInstanceProperty(prop); } @Override - Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceProperty> properties) { + public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String cmptInstanceId, List<ComponentInstanceProperty> properties) { log.debug("#updatePropertiesValues - updating component instance properties for instance {} on component {}", cmptInstanceId, component.getUniqueId()); Map<String, List<ComponentInstanceProperty>> instProperties = Collections.singletonMap(cmptInstanceId, properties); return toscaOperationFacade.addComponentInstancePropertiesToComponent(component, instProperties); } @Override - Optional<ComponentInstance> resolvePropertiesOwner(Component component, String propertiesOwnerId) { + public Optional<ComponentInstance> resolvePropertiesOwner(Component component, String propertiesOwnerId) { log.debug("#resolvePropertiesOwner - fetching component instance {} of component {}", propertiesOwnerId, component.getUniqueId()); return component.getComponentInstanceById(propertiesOwnerId); } @Override - void addPropertiesListToInput(ComponentInstanceProperty declaredProp, InputDefinition input) { + public void addPropertiesListToInput(ComponentInstanceProperty declaredProp, InputDefinition input) { List<ComponentInstanceProperty> propertiesList = input.getProperties(); if(propertiesList == null) { propertiesList = new ArrayList<>(); // adding the property with the new value for UI diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java index 7f49e389ef..d382499172 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/ComponentPropertyDeclarator.java @@ -18,6 +18,10 @@ package org.openecomp.sdc.be.components.property; import fj.data.Either; import org.apache.commons.collections.CollectionUtils; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; @@ -30,11 +34,6 @@ import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - @org.springframework.stereotype.Component public class ComponentPropertyDeclarator extends DefaultPropertyDeclarator<Component, PropertyDataDefinition> { @@ -52,12 +51,12 @@ public class ComponentPropertyDeclarator extends DefaultPropertyDeclarator<Compo } @Override - PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { + public PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { return new PropertyDataDefinition(prop); } @Override - Either<?, StorageOperationStatus> updatePropertiesValues(Component component, + public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId, List<PropertyDataDefinition> properties) { if(CollectionUtils.isNotEmpty(properties)) { @@ -74,12 +73,12 @@ public class ComponentPropertyDeclarator extends DefaultPropertyDeclarator<Compo } @Override - Optional<Component> resolvePropertiesOwner(Component component, String propertiesOwnerId) { - return Optional.of( component); + public Optional<Component> resolvePropertiesOwner(Component component, String propertiesOwnerId) { + return Optional.of(component); } @Override - void addPropertiesListToInput(PropertyDataDefinition declaredProp, + public void addPropertiesListToInput(PropertyDataDefinition declaredProp, InputDefinition input) { List<ComponentInstanceProperty> propertiesList = input.getProperties(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java index 0f76210a1a..02b261b132 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/DefaultPropertyDeclarator.java @@ -1,16 +1,35 @@ package org.openecomp.sdc.be.components.property; +import static org.openecomp.sdc.common.api.Constants.GET_INPUT; +import static org.openecomp.sdc.common.api.Constants.GET_POLICY; + import com.google.gson.Gson; import fj.data.Either; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.json.simple.JSONObject; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PropertiesOwner; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstancePropInput; +import org.openecomp.sdc.be.model.IComponentInstanceConnectedElement; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; @@ -19,11 +38,6 @@ import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.yaml.snakeyaml.Yaml; -import java.util.*; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.common.api.Constants.GET_INPUT; - public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends PropertiesOwner, PROPERTYTYPE extends PropertyDataDefinition> implements PropertyDeclarator { private static final Logger log = Logger.getLogger(DefaultPropertyDeclarator.class); @@ -45,13 +59,35 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId))); } - abstract PROPERTYTYPE createDeclaredProperty(PropertyDataDefinition prop); + protected abstract PROPERTYTYPE createDeclaredProperty(PropertyDataDefinition prop); + + protected abstract Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId, List<PROPERTYTYPE> properties); + + protected abstract Optional<PROPERTYOWNER> resolvePropertiesOwner(Component component, String propertiesOwnerId); + + protected abstract void addPropertiesListToInput(PROPERTYTYPE declaredProp, InputDefinition input); + + @Override + public Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, + String propertiesOwnerId, + List<ComponentInstancePropInput> propsToDeclare) { + log.debug("#declarePropertiesAsPolicies - declaring properties as policies for component {} from properties owner {}", component.getUniqueId(), propertiesOwnerId); + return resolvePropertiesOwner(component, propertiesOwnerId) + .map(propertyOwner -> declarePropertiesAsPolicies(component, propertyOwner, propsToDeclare)) + .orElse(Either.right(onPropertiesOwnerNotFound(component.getUniqueId(), propertiesOwnerId))); - abstract Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String propertiesOwnerId, List<PROPERTYTYPE> properties); + } - abstract Optional<PROPERTYOWNER> resolvePropertiesOwner(Component component, String propertiesOwnerId); + public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy) { + return StorageOperationStatus.OK; + } - abstract void addPropertiesListToInput(PROPERTYTYPE declaredProp, InputDefinition input); + private Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, PROPERTYOWNER propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) { + PropertiesDeclarationData policyProperties = createPoliciesAndOverridePropertiesValues(propertiesOwner.getUniqueId(), propertiesOwner, propsToDeclare); + return updatePropertiesValues(component, propertiesOwner.getUniqueId(), policyProperties.getPropertiesToUpdate()) + .left() + .map(updatePropsRes -> policyProperties.getPoliciesToCreate()); + } private StorageOperationStatus onPropertiesOwnerNotFound(String componentId, String propertiesOwnerId) { log.debug("#declarePropertiesAsInputs - properties owner {} was not found on component {}", propertiesOwnerId, componentId); @@ -64,13 +100,67 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties .left() .map(updatePropsRes -> inputsProperties.getInputsToCreate()); } + private PropertiesDeclarationData createPoliciesAndOverridePropertiesValues(String componentId, PROPERTYOWNER propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) { + List<PROPERTYTYPE> declaredProperties = new ArrayList<>(); + List<PolicyDefinition> policies = new ArrayList<>(); + propsToDeclare.forEach(property -> policies.add(declarePropertyPolicy(componentId, declaredProperties, property))); + return new PropertiesDeclarationData(null, policies, declaredProperties); + } + + private PolicyDefinition declarePropertyPolicy(String componentId, List<PROPERTYTYPE> declaredProperties, + ComponentInstancePropInput propInput) { + PropertyDataDefinition prop = resolveProperty(declaredProperties, propInput); + propInput.setOwnerId(null); + propInput.setParentUniqueId(null); + + PolicyDefinition policyDefinition = new PolicyDefinition(prop); + policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentId, prop.getName())); + policyDefinition.setInputPath(prop.getName()); + policyDefinition.setInstanceUniqueId(componentId); + + changePropertyValueToGetPolicy(prop, policyDefinition); + PROPERTYTYPE declaredProperty = createDeclaredProperty(prop); + + + if(!declaredProperties.contains(declaredProperty)){ + declaredProperties.add(declaredProperty); + } + + return policyDefinition; + } + + private void changePropertyValueToGetPolicy(PropertyDataDefinition prop, PolicyDefinition policyDefinition) { + JSONObject jobject = new JSONObject(); + + String origValue = Objects.isNull(prop.getValue()) ? prop.getDefaultValue() : prop.getValue(); + jobject.put(GET_POLICY, null); + prop.setValue(jobject.toJSONString()); + policyDefinition.setValue(jobject.toJSONString()); + + if(CollectionUtils.isEmpty(prop.getGetPolicyValues())){ + prop.setGetPolicyValues(new ArrayList<>()); + } + List<GetPolicyValueDataDefinition> getPolicyValues = prop.getGetPolicyValues(); + + GetPolicyValueDataDefinition getPolicyValueDataDefinition = new GetPolicyValueDataDefinition(); + getPolicyValueDataDefinition.setPolicyId(policyDefinition.getUniqueId()); + getPolicyValueDataDefinition.setPropertyName(prop.getName()); + + getPolicyValueDataDefinition.setOrigPropertyValue(origValue); + + getPolicyValues.add(getPolicyValueDataDefinition); + + policyDefinition.setGetPolicyValues(getPolicyValues); + + } + private PropertiesDeclarationData createInputsAndOverridePropertiesValues(String componentId, PROPERTYOWNER propertiesOwner, List<ComponentInstancePropInput> propsToDeclare) { List<PROPERTYTYPE> declaredProperties = new ArrayList<>(); List<InputDefinition> createdInputs = propsToDeclare.stream() .map(propInput -> declarePropertyInput(componentId, propertiesOwner, declaredProperties, propInput)) .collect(Collectors.toList()); - return new PropertiesDeclarationData(createdInputs, declaredProperties); + return new PropertiesDeclarationData(createdInputs, null, declaredProperties); } private InputDefinition declarePropertyInput(String componentId, PROPERTYOWNER propertiesOwner, List<PROPERTYTYPE> declaredProperties, ComponentInstancePropInput propInput) { @@ -292,10 +382,12 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties private class PropertiesDeclarationData { private List<InputDefinition> inputsToCreate; + private List<PolicyDefinition> policiesToCreate; private List<PROPERTYTYPE> propertiesToUpdate; - PropertiesDeclarationData(List<InputDefinition> inputsToCreate, List<PROPERTYTYPE> propertiesToUpdate) { + PropertiesDeclarationData(List<InputDefinition> inputsToCreate, List<PolicyDefinition> policiesToCreate, List<PROPERTYTYPE> propertiesToUpdate) { this.inputsToCreate = inputsToCreate; + this.policiesToCreate = policiesToCreate; this.propertiesToUpdate = propertiesToUpdate; } @@ -303,6 +395,8 @@ public abstract class DefaultPropertyDeclarator<PROPERTYOWNER extends Properties return inputsToCreate; } + public List<PolicyDefinition> getPoliciesToCreate() { return policiesToCreate; } + List<PROPERTYTYPE> getPropertiesToUpdate() { return propertiesToUpdate; } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GroupPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GroupPropertyDeclarator.java index 7817d51658..46ca85c585 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GroupPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/GroupPropertyDeclarator.java @@ -20,7 +20,16 @@ package org.openecomp.sdc.be.components.property; +import static java.util.stream.Collectors.toList; +import static org.apache.commons.collections.CollectionUtils.isEmpty; +import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; + import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -33,12 +42,6 @@ import org.openecomp.sdc.be.model.operations.impl.GroupOperation; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.*; - -import static java.util.stream.Collectors.toList; -import static org.apache.commons.collections.CollectionUtils.isEmpty; -import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; - @org.springframework.stereotype.Component public class GroupPropertyDeclarator extends DefaultPropertyDeclarator<GroupDefinition, PropertyDataDefinition> { @@ -51,25 +54,25 @@ public class GroupPropertyDeclarator extends DefaultPropertyDeclarator<GroupDefi } @Override - PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { + public PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { return new PropertyDataDefinition(prop); } @Override - Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String groupId, List<PropertyDataDefinition> properties) { + public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String groupId, List<PropertyDataDefinition> properties) { log.debug("#updatePropertiesValues - updating group properties for group {} on component {}", groupId, component.getUniqueId()); StorageOperationStatus updateStatus = groupOperation.updateGroupProperties(component, groupId, properties); return updateStatus == StorageOperationStatus.OK ? Either.left(updateStatus) : Either.right(updateStatus); } @Override - Optional<GroupDefinition> resolvePropertiesOwner(Component component, String groupId) { + public Optional<GroupDefinition> resolvePropertiesOwner(Component component, String groupId) { log.debug("#resolvePropertiesOwner - fetching group {} of component {}", groupId, component.getUniqueId()); return component.getGroupById(groupId); } @Override - void addPropertiesListToInput(PropertyDataDefinition declaredProp, InputDefinition input) { + public void addPropertiesListToInput(PropertyDataDefinition declaredProp, InputDefinition input) { List<ComponentInstanceProperty> propertiesList = input.getProperties(); if(propertiesList == null) { propertiesList = new ArrayList<>(); // adding the property with the new value for UI diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java index 9f150aa336..f7f4a75be1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PolicyPropertyDeclarator.java @@ -19,7 +19,15 @@ */ package org.openecomp.sdc.be.components.property; +import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; + import fj.data.Either; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -32,11 +40,6 @@ import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.*; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput; - @org.springframework.stereotype.Component public class PolicyPropertyDeclarator extends DefaultPropertyDeclarator<PolicyDefinition, PropertyDataDefinition> { @@ -49,25 +52,25 @@ public class PolicyPropertyDeclarator extends DefaultPropertyDeclarator<PolicyDe } @Override - PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { + public PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { return new PropertyDataDefinition(prop); } @Override - Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String policyId, List<PropertyDataDefinition> properties) { + public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String policyId, List<PropertyDataDefinition> properties) { log.debug("#updatePropertiesValues - updating policies properties for policy {} on component {}", policyId, component.getUniqueId()); StorageOperationStatus updateStatus = policyOperation.updatePolicyProperties(component, policyId, properties); return updateStatus == StorageOperationStatus.OK ? Either.left(updateStatus) : Either.right(updateStatus); } @Override - Optional<PolicyDefinition> resolvePropertiesOwner(Component component, String policyId) { + public Optional<PolicyDefinition> resolvePropertiesOwner(Component component, String policyId) { log.debug("#resolvePropertiesOwner - fetching policy {} of component {}", policyId, component.getUniqueId()); return Optional.ofNullable(component.getPolicyById(policyId)); } @Override - void addPropertiesListToInput(PropertyDataDefinition declaredProp, InputDefinition input) { + public void addPropertiesListToInput(PropertyDataDefinition declaredProp, InputDefinition input) { List<ComponentInstanceProperty> propertiesList = input.getProperties(); if(propertiesList == null) { propertiesList = new ArrayList<>(); // adding the property with the new value for UI diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarationOrchestrator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarationOrchestrator.java index babddc4da1..3a32559dda 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarationOrchestrator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarationOrchestrator.java @@ -1,19 +1,21 @@ package org.openecomp.sdc.be.components.property; +import static org.apache.commons.collections.MapUtils.isNotEmpty; + import fj.data.Either; +import java.util.Arrays; +import java.util.List; import org.apache.commons.lang3.tuple.Pair; +import org.openecomp.sdc.be.components.property.propertytopolicydeclarators.ComponentInstancePropertyToPolicyDeclarator; +import org.openecomp.sdc.be.components.property.propertytopolicydeclarators.ComponentPropertyToPolicyDeclarator; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstInputsMap; import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.util.Arrays; -import java.util.List; - -import static org.apache.commons.collections.MapUtils.isNotEmpty; - @org.springframework.stereotype.Component public class PropertyDeclarationOrchestrator { @@ -23,20 +25,25 @@ public class PropertyDeclarationOrchestrator { private PolicyPropertyDeclarator policyPropertyDeclarator; private GroupPropertyDeclarator groupPropertyDeclarator; private ComponentPropertyDeclarator servicePropertyDeclarator; - private List<PropertyDeclarator> propertyDeclarators; + private List<PropertyDeclarator> propertyDeclaratorsToInput; + private List<PropertyDeclarator> propertyDeclaratorsToPolicy; + private ComponentPropertyToPolicyDeclarator componentPropertyToPolicyDeclarator; + private ComponentInstancePropertyToPolicyDeclarator componentInstancePropertyToPolicyDeclarator; - public PropertyDeclarationOrchestrator( - ComponentInstanceInputPropertyDeclarator componentInstanceInputPropertyDeclarator, - ComponentInstancePropertyDeclarator componentInstancePropertyDeclarator, - PolicyPropertyDeclarator policyPropertyDeclarator, - GroupPropertyDeclarator groupPropertyDeclarator, - ComponentPropertyDeclarator servicePropertyDeclarator) { + public PropertyDeclarationOrchestrator(ComponentInstanceInputPropertyDeclarator componentInstanceInputPropertyDeclarator, + ComponentInstancePropertyDeclarator componentInstancePropertyDeclarator, PolicyPropertyDeclarator policyPropertyDeclarator, + GroupPropertyDeclarator groupPropertyDeclarator, ComponentPropertyDeclarator servicePropertyDeclarator, + ComponentPropertyToPolicyDeclarator componentPropertyToPolicyDeclarator, + ComponentInstancePropertyToPolicyDeclarator componentInstancePropertyToPolicyDeclarator) { this.componentInstanceInputPropertyDeclarator = componentInstanceInputPropertyDeclarator; this.componentInstancePropertyDeclarator = componentInstancePropertyDeclarator; this.policyPropertyDeclarator = policyPropertyDeclarator; this.groupPropertyDeclarator = groupPropertyDeclarator; this.servicePropertyDeclarator = servicePropertyDeclarator; - propertyDeclarators = Arrays.asList(componentInstanceInputPropertyDeclarator, componentInstancePropertyDeclarator, policyPropertyDeclarator, groupPropertyDeclarator, servicePropertyDeclarator); + this.componentPropertyToPolicyDeclarator = componentPropertyToPolicyDeclarator; + this.componentInstancePropertyToPolicyDeclarator = componentInstancePropertyToPolicyDeclarator; + propertyDeclaratorsToInput = Arrays.asList(componentInstanceInputPropertyDeclarator, componentInstancePropertyDeclarator, policyPropertyDeclarator, groupPropertyDeclarator, servicePropertyDeclarator); + propertyDeclaratorsToPolicy = Arrays.asList(componentPropertyToPolicyDeclarator, componentInstancePropertyToPolicyDeclarator); } public Either<List<InputDefinition>, StorageOperationStatus> declarePropertiesToInputs(Component component, ComponentInstInputsMap componentInstInputsMap) { @@ -45,9 +52,15 @@ public class PropertyDeclarationOrchestrator { return propertyDeclarator.declarePropertiesAsInputs(component, propsToDeclare.getLeft(), propsToDeclare.getRight()); } + public Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesToPolicies(Component component, ComponentInstInputsMap componentInstInputsMap) { + PropertyDeclarator propertyDeclarator = getPropertyDeclarator(componentInstInputsMap); + Pair<String, List<ComponentInstancePropInput>> propsToDeclare = componentInstInputsMap.resolvePropertiesToDeclare(); + return propertyDeclarator.declarePropertiesAsPolicies(component, propsToDeclare.getLeft(), propsToDeclare.getRight()); + } + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition inputToDelete) { log.debug("#unDeclarePropertiesAsInputs - removing input declaration for input {} on component {}", inputToDelete.getName(), component.getUniqueId()); - for (PropertyDeclarator propertyDeclarator : propertyDeclarators) { + for (PropertyDeclarator propertyDeclarator : propertyDeclaratorsToInput) { StorageOperationStatus storageOperationStatus = propertyDeclarator.unDeclarePropertiesAsInputs(component, inputToDelete); if (StorageOperationStatus.OK != storageOperationStatus) { log.debug("#unDeclarePropertiesAsInputs - failed to remove input declaration for input {} on component {}. reason {}", inputToDelete.getName(), component.getUniqueId(), storageOperationStatus); @@ -58,6 +71,23 @@ public class PropertyDeclarationOrchestrator { } + public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policyToDelete) { + log.debug("#unDeclarePropertiesAsInputs - removing policy declaration for input {} on component {}", policyToDelete + .getName(), component.getUniqueId()); + for(PropertyDeclarator propertyDeclarator : propertyDeclaratorsToPolicy) { + StorageOperationStatus storageOperationStatus = + propertyDeclarator.unDeclarePropertiesAsPolicies(component, policyToDelete); + if (StorageOperationStatus.OK != storageOperationStatus) { + log.debug("#unDeclarePropertiesAsInputs - failed to remove policy declaration for policy {} on component {}. reason {}", policyToDelete + .getName(), component.getUniqueId(), storageOperationStatus); + return storageOperationStatus; + } + } + + return StorageOperationStatus.OK; + + } + private PropertyDeclarator getPropertyDeclarator(ComponentInstInputsMap componentInstInputsMap) { if (isNotEmpty(componentInstInputsMap.getComponentInstanceInputsMap())) { return componentInstanceInputPropertyDeclarator; @@ -74,6 +104,12 @@ public class PropertyDeclarationOrchestrator { if(isNotEmpty(componentInstInputsMap.getServiceProperties())) { return servicePropertyDeclarator; } + if(isNotEmpty(componentInstInputsMap.getComponentPropertiesToPolicies())) { + return componentPropertyToPolicyDeclarator; + } + if(isNotEmpty(componentInstInputsMap.getComponentInstancePropertiesToPolicies())) { + return componentInstancePropertyToPolicyDeclarator; + } throw new IllegalStateException("there are no properties selected for declaration"); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarator.java index a5add358d7..c0f76288b2 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/PropertyDeclarator.java @@ -1,13 +1,13 @@ package org.openecomp.sdc.be.components.property; import fj.data.Either; +import java.util.List; import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.ComponentInstancePropInput; import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import java.util.List; - public interface PropertyDeclarator { /** @@ -27,4 +27,21 @@ public interface PropertyDeclarator { */ StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input); + /** + * creates a list of policies from the given list of properties and updates the properties accordingly + * @param component the container + * @param propertiesOwnerId the id of the owner of the properties to declare (e.g ComponentInstance, Policy, Group etc) + * @param propsToDeclare the list of properties that are being declared as inputs + * @return the list of policies that were created from the given properties + */ + Either<List<PolicyDefinition>, StorageOperationStatus> declarePropertiesAsPolicies(Component component, String propertiesOwnerId, List<ComponentInstancePropInput> propsToDeclare); + + /** + * returns the values of declared properties to each original state before it was declared as an policy. + * this function is to be called when an policy, that was created by declaring a property, is deleted. + * @param component the container of the input to be deleted + * @param policy the policy to be deleted + */ + StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy); + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java new file mode 100644 index 0000000000..bbbdf6f105 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentInstancePropertyToPolicyDeclarator.java @@ -0,0 +1,81 @@ +package org.openecomp.sdc.be.components.property.propertytopolicydeclarators; + +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.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.property.DefaultPropertyDeclarator; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; + +@org.springframework.stereotype.Component +public class ComponentInstancePropertyToPolicyDeclarator extends + DefaultPropertyDeclarator<ComponentInstance, ComponentInstanceProperty> { + + private ToscaOperationFacade toscaOperationFacade; + PropertyBusinessLogic propertyBl; + private ComponentInstanceBusinessLogic componentInstanceBl; + + public ComponentInstancePropertyToPolicyDeclarator(ComponentsUtils componentsUtils, + PropertyOperation propertyOperation, ToscaOperationFacade toscaOperationFacade, + PropertyBusinessLogic propertyBl, ComponentInstanceBusinessLogic componentInstanceBl) { + super(componentsUtils, propertyOperation); + this.toscaOperationFacade = toscaOperationFacade; + this.propertyBl = propertyBl; + this.componentInstanceBl = componentInstanceBl; + } + + @Override + protected ComponentInstanceProperty createDeclaredProperty(PropertyDataDefinition prop) { + return new ComponentInstanceProperty(prop); + } + + @Override + protected Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String componentInstanceId, + List<ComponentInstanceProperty> properties) { + Map<String, List<ComponentInstanceProperty>> + instProperties = Collections.singletonMap(componentInstanceId, properties); + return toscaOperationFacade.addComponentInstancePropertiesToComponent(component, instProperties); + } + + @Override + protected Optional<ComponentInstance> resolvePropertiesOwner(Component component, String componentInstanceId) { + return component.getComponentInstanceById(componentInstanceId); + } + + @Override + protected void addPropertiesListToInput(ComponentInstanceProperty declaredProp, InputDefinition input) { + return; + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) { + return StorageOperationStatus.OK; + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy) { + + Optional<ComponentInstanceProperty> propertyCandidate = + componentInstanceBl.getComponentInstancePropertyByPolicyId(component, policy); + + + if(propertyCandidate.isPresent()) { + return toscaOperationFacade + .updateComponentInstanceProperty(component, policy.getInstanceUniqueId(), propertyCandidate.get()); + } + + return StorageOperationStatus.OK; + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java new file mode 100644 index 0000000000..1d73786938 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/property/propertytopolicydeclarators/ComponentPropertyToPolicyDeclarator.java @@ -0,0 +1,137 @@ +package org.openecomp.sdc.be.components.property.propertytopolicydeclarators; + +import fj.data.Either; +import java.util.List; +import java.util.Optional; +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.property.DefaultPropertyDeclarator; +import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.PolicyDefinition; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.PropertyOperation; + +@org.springframework.stereotype.Component +public class ComponentPropertyToPolicyDeclarator extends DefaultPropertyDeclarator<Component, PropertyDataDefinition> { + + private ToscaOperationFacade toscaOperationFacade; + PropertyBusinessLogic propertyBL; + + + public ComponentPropertyToPolicyDeclarator(ComponentsUtils componentsUtils, PropertyOperation propertyOperation, + ToscaOperationFacade toscaOperationFacade, PropertyBusinessLogic propertyBusinessLogic) { + super(componentsUtils, propertyOperation); + this.toscaOperationFacade = toscaOperationFacade; + this.propertyBL = propertyBusinessLogic; + } + + @Override + public PropertyDataDefinition createDeclaredProperty(PropertyDataDefinition prop) { + return new PropertyDataDefinition(prop); + } + + @Override + public Either<?, StorageOperationStatus> updatePropertiesValues(Component component, String policyId, + List<PropertyDataDefinition> properties) { + if(CollectionUtils.isNotEmpty(properties)) { + for(PropertyDataDefinition property : properties) { + Either<PropertyDefinition, StorageOperationStatus> + storageStatus = toscaOperationFacade + .updatePropertyOfComponent(component, new PropertyDefinition(property)); + if(storageStatus.isRight()) { + return Either.right(storageStatus.right().value()); + } + } + } + return Either.left(properties); + + } + + @Override + public Optional<Component> resolvePropertiesOwner(Component component, String propertyId) { + return Optional.of(component); + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsInputs(Component component, InputDefinition input) { + // no need for implementation since we are in a policy scenario + return StorageOperationStatus.OK; + } + + @Override + public void addPropertiesListToInput(PropertyDataDefinition declaredProp, InputDefinition input) { + // no need for implementation since we are in a policy scenario + return; + } + + @Override + public StorageOperationStatus unDeclarePropertiesAsPolicies(Component component, PolicyDefinition policy) { + Optional<PropertyDefinition> propertyToUpdateCandidate = + getDeclaredPropertyByPolicyId(component, policy.getUniqueId()); + + if(propertyToUpdateCandidate.isPresent()) { + return unDeclarePolicy(component, propertyToUpdateCandidate.get(), policy); + } + + return StorageOperationStatus.OK; + } + + private StorageOperationStatus unDeclarePolicy(Component component, PropertyDefinition propertyToUpdate, PolicyDefinition policy) { + updatePropertyAfterUndeclaration(propertyToUpdate, policy); + + Either<PropertyDefinition, StorageOperationStatus> status = toscaOperationFacade + .updatePropertyOfComponent(component, propertyToUpdate); + if(status.isRight()) { + return status.right().value(); + } + + return StorageOperationStatus.OK; + } + + private void updatePropertyAfterUndeclaration(PropertyDefinition propertyToUpdate, PolicyDefinition policy) { + List<GetPolicyValueDataDefinition> getPolicyValues = propertyToUpdate.getGetPolicyValues(); + Optional<GetPolicyValueDataDefinition> getPolicyCandidateToRemove = getPolicyValues.stream() + .filter(getPolicyValue -> getPolicyValue.getPolicyId() + .equals(policy.getUniqueId())) + .findAny(); + + getPolicyCandidateToRemove.ifPresent(getPolicyValue -> { + getPolicyValues.remove(getPolicyValue); + propertyToUpdate.setValue(getPolicyValue.getOrigPropertyValue()); + }); + } + + private Optional<PropertyDefinition> getDeclaredPropertyByPolicyId(Component component, + String policyId) { + List<PropertyDefinition> properties = component.getProperties(); + + if(CollectionUtils.isEmpty(properties)) { + return Optional.empty(); + } + + for(PropertyDefinition propertyDefinition : properties) { + List<GetPolicyValueDataDefinition> getPolicyValues = propertyDefinition.getGetPolicyValues(); + if(CollectionUtils.isEmpty(getPolicyValues)) { + continue; + } + + + Optional<GetPolicyValueDataDefinition> getPolicyCandidate = + getPolicyValues.stream().filter(getPolicy -> getPolicy.getPolicyId().equals(policyId)).findAny(); + + if(getPolicyCandidate.isPresent()) { + propertyDefinition.setValue(getPolicyCandidate.get().getOrigPropertyValue()); + return Optional.of(propertyDefinition); + } + } + + return Optional.empty(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java index 80747b5991..e9d96983aa 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/PolicyUtils.java @@ -1,28 +1,29 @@ package org.openecomp.sdc.be.components.validation; +import static org.apache.commons.collections.MapUtils.isEmpty; +import static org.apache.commons.collections.MapUtils.isNotEmpty; +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; +import static org.openecomp.sdc.common.api.Constants.GROUP_POLICY_NAME_DELIMETER; + import fj.data.Either; +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.ValidationUtils; -import java.util.Collections; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -import static org.apache.commons.collections.MapUtils.isEmpty; -import static org.apache.commons.collections.MapUtils.isNotEmpty; -import static org.apache.commons.lang3.StringUtils.isEmpty; -import static org.apache.commons.lang3.StringUtils.isNotEmpty; -import static org.openecomp.sdc.common.api.Constants.GROUP_POLICY_NAME_DELIMETER; - /** * Provides specific functionality for policy */ @@ -94,6 +95,14 @@ public class PolicyUtils { .get(((Resource) component).getResourceType().getValue()); } + public static PolicyDefinition getDeclaredPolicyDefinition(String componentInstanceId, ComponentInstanceProperty property) { + PolicyDefinition policyDefinition = new PolicyDefinition(property); + policyDefinition.setUniqueId(UniqueIdBuilder.buildPolicyUniqueId(componentInstanceId, property.getName())); + policyDefinition.setInstanceUniqueId(componentInstanceId); + + return policyDefinition; + } + private static int extractNextPolicyCounterFromUniqueId(String uniqueId) { int counter = 0; if (isNotEmpty(uniqueId)) { diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtil.java index f2cdcc3a6d..073e469c1e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/PropertyValueConstraintValidationUtil.java @@ -16,6 +16,8 @@ package org.openecomp.sdc.be.datamodel.utils; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; @@ -30,8 +32,6 @@ import org.apache.commons.collections4.ListUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; -import org.codehaus.jackson.map.ObjectMapper; -import org.codehaus.jackson.type.TypeReference; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.model.DataTypeDefinition; 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 0dddfe5c13..858d15ab9e 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 @@ -26,12 +26,17 @@ import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.components.impl.GroupTypeBusinessLogic; import org.openecomp.sdc.be.components.impl.PolicyTypeBusinessLogic; +import org.openecomp.sdc.be.components.validation.PolicyUtils; import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.components.ServiceMetadataDataDefinition; import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition; @@ -39,6 +44,7 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.CapabilityDefinition; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; import org.openecomp.sdc.be.model.GroupDefinition; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.Resource; @@ -94,7 +100,7 @@ public class UiComponentDataConverter { setCapabilities(dataTransfer, component); break; case POLICIES: - dataTransfer.setPolicies(component.resolvePoliciesList()); + setPolicies(dataTransfer, component); break; case NON_EXCLUDED_POLICIES: setNonExcludedPolicies(dataTransfer, component); @@ -139,6 +145,33 @@ public class UiComponentDataConverter { } } + private void setPolicies(UiComponentDataTransfer dataTransfer, Component component) { + Map<String, PolicyDefinition> policies = component.getPolicies(); + Set<PolicyDefinition> policyDefinitions = + MapUtils.isEmpty(policies) ? new HashSet<>() : new HashSet<>(policies.values()); + + policyDefinitions.addAll(getDeclaredPolicies(component.getComponentInstancesProperties())); + + dataTransfer.setPolicies(new ArrayList<>(policyDefinitions)); + } + + private Set<PolicyDefinition> getDeclaredPolicies(Map<String, List<ComponentInstanceProperty>> componentInstanceProperties) { + if(MapUtils.isEmpty(componentInstanceProperties)) { + return new HashSet<>(); + } + + Set<PolicyDefinition> declaredPolicies = new HashSet<>(); + for(Map.Entry<String, List<ComponentInstanceProperty>> instancePropertyEntry : componentInstanceProperties.entrySet()) { + declaredPolicies.addAll(instancePropertyEntry.getValue().stream() + .filter(property -> CollectionUtils.isNotEmpty(property.getGetPolicyValues())) + .map(instanceProperty -> PolicyUtils.getDeclaredPolicyDefinition(instancePropertyEntry.getKey(), instanceProperty)) + .collect(Collectors.toSet())); + } + + return declaredPolicies; + } + + private void setComponentInstanceRelation(UiComponentDataTransfer dataTransfer, Component component) { if (component.getComponentInstancesRelations() == null) { dataTransfer.setComponentInstancesRelations(new ArrayList<>()); @@ -367,6 +400,15 @@ public class UiComponentDataConverter { UiServiceMetadata metadata = new UiServiceMetadata(service.getCategories(), (ServiceMetadataDataDefinition) service.getComponentMetadataDefinition().getMetadataDataDefinition()); dataTransfer.setMetadata(metadata); break; + case NODE_FILTER: + if(service.getNodeFilterComponents() == null) { + dataTransfer.setNodeFilterData(null); + } else { + NodeFilterConverter nodeFilterConverter = new NodeFilterConverter(); + dataTransfer.setNodeFilterData(nodeFilterConverter.convertDataMapToUI(service.getNodeFilterComponents())); + } + + break; default: setUiTranferDataByFieldName(dataTransfer, service, fieldName); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyCompositionMixin.java b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyCompositionMixin.java index 7e479eadfe..775a7d9f78 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyCompositionMixin.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/mixin/PolicyCompositionMixin.java @@ -1,14 +1,13 @@ package org.openecomp.sdc.be.mixin; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.be.datatypes.elements.PolicyDataDefinition; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.view.Mixin; import org.openecomp.sdc.be.view.MixinTarget; -import java.util.List; -import java.util.Map; - @MixinTarget(target = PolicyDataDefinition.class) public abstract class PolicyCompositionMixin extends Mixin { @JsonProperty @@ -19,6 +18,12 @@ public abstract class PolicyCompositionMixin extends Mixin { abstract String getUniqueId(); @JsonProperty("type") abstract String getPolicyTypeName(); + @JsonProperty + abstract String getInputPath(); + @JsonProperty + abstract String getValue(); + @JsonProperty + abstract String getInstanceUniqueId(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java index 14fc77acd5..3d7dd8c622 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/AbstractValidationsServlet.java @@ -24,6 +24,21 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import fj.data.Either; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; @@ -62,19 +77,6 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.web.context.WebApplicationContext; import org.yaml.snakeyaml.Yaml; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; -import java.io.*; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; -import java.util.zip.ZipInputStream; - public abstract class AbstractValidationsServlet extends BeGenericServlet { private static final Logger log = Logger.getLogger(AbstractValidationsServlet.class); @@ -786,8 +788,6 @@ public abstract class AbstractValidationsServlet extends BeGenericServlet { protected void validateComponentInstanceBusinessLogic(HttpServletRequest request, String containerComponentType, Wrapper<ComponentInstanceBusinessLogic> blWrapper, Wrapper<ResponseFormat> errorWrapper) { ServletContext context = request.getSession().getServletContext(); - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); ComponentInstanceBusinessLogic componentInstanceLogic = getComponentInstanceBL(context); if (componentInstanceLogic == null) { log.debug("Unsupported component type {}", containerComponentType); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java index 94431f6b48..b397439a99 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/BeGenericServlet.java @@ -27,20 +27,53 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import fj.data.Either; +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.function.Supplier; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; -import org.openecomp.sdc.be.components.impl.*; +import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic; +import org.openecomp.sdc.be.components.impl.BaseBusinessLogic; +import org.openecomp.sdc.be.components.impl.CapabilitiesBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ElementBusinessLogic; +import org.openecomp.sdc.be.components.impl.GenericArtifactBrowserBusinessLogic; +import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; +import org.openecomp.sdc.be.components.impl.InputsBusinessLogic; +import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic; +import org.openecomp.sdc.be.components.impl.MonitoringBusinessLogic; +import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; +import org.openecomp.sdc.be.components.impl.ProductBusinessLogic; +import org.openecomp.sdc.be.components.impl.PropertyBusinessLogic; +import org.openecomp.sdc.be.components.impl.RelationshipTypeBusinessLogic; +import org.openecomp.sdc.be.components.impl.RequirementBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; import org.openecomp.sdc.be.components.scheduledtasks.ComponentsCleanBusinessLogic; import org.openecomp.sdc.be.components.upgrade.UpgradeBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; import org.openecomp.sdc.be.model.PropertyConstraint; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.User; @@ -56,19 +89,6 @@ import org.openecomp.sdc.common.servlets.BasicServlet; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.web.context.WebApplicationContext; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.ResponseBuilder; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.function.Supplier; - public class BeGenericServlet extends BasicServlet { @Context @@ -433,4 +453,70 @@ public class BeGenericServlet extends BasicServlet { PropertyBusinessLogic propertytBl = webApplicationContext.getBean(PropertyBusinessLogic.class); return propertytBl; } + + protected InputsBusinessLogic getInputBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(InputsBusinessLogic.class); + } + + protected PolicyBusinessLogic getPolicyBL(ServletContext context) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(PolicyBusinessLogic.class); + } + + protected Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String componentJson, User user, ComponentTypeEnum componentType) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(componentJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, componentType); + } + + protected Response declareProperties(String userId, String componentId, String componentType, + String componentInstInputsMapObj, DeclarationTypeEnum typeEnum, HttpServletRequest request) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + log.debug("(get) Start handle request of {}", url); + Response response = null; + + try { + BaseBusinessLogic businessLogic = getBlForPropertyDeclaration(typeEnum, context); + + // get modifier id + User modifier = new User(); + modifier.setUserId(userId); + log.debug("modifier id is {}", userId); + ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier, componentTypeEnum); + if (componentInstInputsMapRes.isRight()) { + log.debug("failed to parse componentInstInputsMap"); + response = buildErrorResponse(componentInstInputsMapRes.right().value()); + return response; + } + + Either<List<ToscaDataDefinition>, ResponseFormat> propertiesAfterDeclaration = businessLogic + .declareProperties(userId, componentId, + componentTypeEnum, + componentInstInputsMapRes.left().value()); + if (propertiesAfterDeclaration.isRight()) { + log.debug("failed to create inputs for service: {}", componentId); + return buildErrorResponse(propertiesAfterDeclaration.right().value()); + } + Object properties = RepresentationUtils.toRepresentation(propertiesAfterDeclaration.left().value()); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId); + log.debug("Properties declaration failed with exception", e); + response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + return response; + } + } + + public BaseBusinessLogic getBlForPropertyDeclaration(DeclarationTypeEnum typeEnum, + ServletContext context) { + if(typeEnum.equals(DeclarationTypeEnum.POLICY)) { + return getPolicyBL(context); + } + + return getInputBL(context); + } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java index d55f3e9cc3..7da6533570 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InputsServlet.java @@ -23,28 +23,42 @@ package org.openecomp.sdc.be.servlets; import com.fasterxml.jackson.databind.ObjectMapper; import com.jcabi.aspects.Loggable; import fj.data.Either; -import io.swagger.annotations.*; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import java.util.Arrays; +import java.util.List; +import javax.inject.Singleton; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +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.InputsBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.*; +import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstInputsMap; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.ComponentInstanceProperty; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; -import org.springframework.web.context.WebApplicationContext; - -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.Arrays; -import java.util.List; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) @Api(value = "Input Catalog", description = "Input Servlet") @@ -242,10 +256,6 @@ public class InputsServlet extends AbstractValidationsServlet { } } - private Either<ComponentInstInputsMap, ResponseFormat> parseToComponentInstanceMap(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, ComponentInstInputsMap.class, AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); - } - @POST @Path("/{componentType}/{componentId}/create/inputs") @ApiOperation(value = "Create inputs on service", httpMethod = "POST", notes = "Return inputs list", response = Resource.class) @@ -253,43 +263,8 @@ public class InputsServlet extends AbstractValidationsServlet { public Response createMultipleInputs(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns Inputs Object to be created", required = true) String componentInstInputsMapObj) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug("(get) Start handle request of {}", url); - Response response = null; - - try { - InputsBusinessLogic businessLogic = getInputBL(context); - - // get modifier id - User modifier = new User(); - modifier.setUserId(userId); - log.debug("modifier id is {}", userId); - - Either<ComponentInstInputsMap, ResponseFormat> componentInstInputsMapRes = parseToComponentInstanceMap(componentInstInputsMapObj, modifier); - if (componentInstInputsMapRes.isRight()) { - log.debug("failed to parse componentInstInputsMap"); - response = buildErrorResponse(componentInstInputsMapRes.right().value()); - return response; - } - - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); - ComponentInstInputsMap componentInstInputsMap = componentInstInputsMapRes.left().value(); - - Either<List<InputDefinition>, ResponseFormat> inputPropertiesRes = businessLogic.createMultipleInputs(userId, componentId, componentTypeEnum, componentInstInputsMap, true, false); - if (inputPropertiesRes.isRight()) { - log.debug("failed to create inputs for service: {}", componentId); - return buildErrorResponse(inputPropertiesRes.right().value()); - } - Object properties = RepresentationUtils.toRepresentation(inputPropertiesRes.left().value()); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), properties); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Create inputs for service with id: " + componentId); - log.debug("createMultipleInputs failed with exception", e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - } + return super.declareProperties(userId, componentId, componentType, componentInstInputsMapObj, + DeclarationTypeEnum.INPUT, request); } @@ -329,10 +304,4 @@ public class InputsServlet extends AbstractValidationsServlet { } } - private InputsBusinessLogic getInputBL(ServletContext context) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(InputsBusinessLogic.class); - } - } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java index 49a827ebec..3208102d1c 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/PolicyServlet.java @@ -2,7 +2,28 @@ package org.openecomp.sdc.be.servlets; import com.jcabi.aspects.Loggable; import fj.data.Either; -import io.swagger.annotations.*; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +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.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.components.impl.PolicyBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; @@ -11,26 +32,18 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datatypes.elements.PolicyTargetType; import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.DeclarationTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ServletUtils; import org.openecomp.sdc.be.model.PolicyDefinition; import org.openecomp.sdc.be.model.PolicyTargetDTO; +import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.stereotype.Controller; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - /** * Provides REST API to create, retrieve, update, delete a policy */ @@ -160,7 +173,7 @@ public class PolicyServlet extends AbstractValidationsServlet { Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); if (responseWrapper.isEmpty()) { responseWrapper.setInnerElement(policyBusinessLogic.deletePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true) - .either(l -> buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.NO_CONTENT), null), + .either(this::buildOkResponse, this::buildErrorResponse)); } @@ -172,6 +185,34 @@ public class PolicyServlet extends AbstractValidationsServlet { return responseWrapper.getInnerElement(); } + @PUT + @Path("/{containerComponentType}/{componentId}/policies/{policyId}/undeclare") + @ApiOperation(value = "undeclare Policy", httpMethod = "PUT", notes = "No body", response = Response.class) + @ApiResponses(value = {@ApiResponse(code = 204, message = "Policy was undeclared"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 404, message = "component / policy Not found")}) + public Response undeclarePolicy(@PathParam("componentId") final String containerComponentId, + @ApiParam(value = "valid values: resources / services", allowableValues = ComponentTypeEnum.RESOURCE_PARAM_NAME + "," + ComponentTypeEnum.SERVICE_PARAM_NAME) @PathParam("containerComponentType") final String containerComponentType, + @PathParam("policyId") final String policyId, @HeaderParam(value = Constants.USER_ID_HEADER) @ApiParam(value = "USER_ID of modifier user", required = true) String userId, + @Context final HttpServletRequest request) { + init(); + + Wrapper<Response> responseWrapper = new Wrapper<>(); + try { + Wrapper<ComponentTypeEnum> componentTypeWrapper = validateComponentTypeAndUserId(containerComponentType, userId, responseWrapper); + if (responseWrapper.isEmpty()) { + responseWrapper.setInnerElement(policyBusinessLogic.undeclarePolicy(componentTypeWrapper.getInnerElement(), containerComponentId, policyId, userId, true) + .either(this::buildOkResponse, + this::buildErrorResponse)); + } + + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Undeclare Policy"); + log.error("Failed to undeclare policy. The exception {} occurred. ", e); + responseWrapper.setInnerElement(buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR))); + } + return responseWrapper.getInnerElement(); + } + @GET @Path("/{containerComponentType}/{componentId}/policies/{policyId}/properties") @ApiOperation(value = "Get component policy properties", httpMethod = "GET", notes = "Returns component policy properties", response = PropertyDataDefinition.class, responseContainer="List") @@ -268,6 +309,17 @@ public class PolicyServlet extends AbstractValidationsServlet { } } + @POST + @Path("/{componentType}/{componentId}/create/policies") + @ApiOperation(value = "Create policies on service", httpMethod = "POST", notes = "Return policies list", response = Resource.class) + @ApiResponses(value = { @ApiResponse(code = 200, message = "Component found"), @ApiResponse(code = 403, message = "Restricted operation"), @ApiResponse(code = 404, message = "Component not found") }) + public Response declareProperties(@PathParam("componentType") final String componentType, @PathParam("componentId") final String componentId, @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @ApiParam(value = "ComponentIns policies Object to be created", required = true) String componentInstPoliciesMapObj) { + + return super.declareProperties(userId, componentId, componentType, componentInstPoliciesMapObj, + DeclarationTypeEnum.POLICY, request); + } + private Either<PolicyDefinition, ResponseFormat> updatePolicyTargetsFromMap(Map<PolicyTargetType, List<String>> policyTarget, String containerComponentType, String containerComponentId, String policyId, String userId) { return convertToComponentType(containerComponentType) .left() |