diff options
Diffstat (limited to 'catalog-be/src/main/java')
9 files changed, 986 insertions, 870 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 a7c926e0f7..544f030d91 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 @@ -240,16 +240,6 @@ public abstract class BaseBusinessLogic { } } - protected ActionStatus lockComponentAndReturnStatus(final String componentId, - final Component component, - final String ecompErrorContext) { - final ActionStatus lock = lockElement(componentId, component, ecompErrorContext); - if (lock!= ActionStatus.OK) { - logAndThrowComponentException(lock, component.getUniqueId(), component.getName()); - } - return ActionStatus.OK; - } - protected void lockComponent(String componentId, Component component, boolean needLock, String ecompErrorContext) { if (needLock) { lockComponent(componentId, component, ecompErrorContext); 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 486a6b2a35..30cfac225b 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 @@ -44,6 +44,7 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; +import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; @@ -73,6 +74,7 @@ import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.ForwardingPathUtils; import org.openecomp.sdc.be.impl.ServiceFilterUtils; import org.openecomp.sdc.be.info.CreateAndAssotiateInfo; @@ -116,6 +118,7 @@ import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.resources.data.ComponentInstanceData; +import org.openecomp.sdc.be.user.Role; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; @@ -150,7 +153,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL; private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator; private ForwardingPathOperation forwardingPathOperation; - private NodeFilterOperation serviceFilterOperation; + private NodeFilterOperation nodeFilterOperation; @Autowired public ComponentInstanceBusinessLogic(IElementOperation elementDao, @@ -162,7 +165,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic, ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL, ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator, - ForwardingPathOperation forwardingPathOperation, NodeFilterOperation serviceFilterOperation, + ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation, ArtifactsOperations artifactToscaOperation) { super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation); @@ -171,7 +174,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { this.compInstMergeDataBL = compInstMergeDataBL; this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator; this.forwardingPathOperation = forwardingPathOperation; - this.serviceFilterOperation = serviceFilterOperation; + this.nodeFilterOperation = nodeFilterOperation; } @Autowired @@ -786,14 +789,20 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true); } - public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction, - boolean needLock) { + public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata( + final String containerComponentParam, + final String containerComponentId, + final String componentInstanceId, + final String userId, + ComponentInstance componentInstance, + final boolean inTransaction, + boolean needLock) { validateUserExists(userId); final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); + final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); validateCanWorkOnComponent(containerComponent, userId); ComponentTypeEnum instanceType = getComponentType(containerComponentType); @@ -1010,7 +1019,7 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { oldInstanceName, newInstanceName); for( Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()){ Either<CINodeFilterDataDefinition, StorageOperationStatus> - renameEither = serviceFilterOperation.updateNodeFilter( + renameEither = nodeFilterOperation.updateNodeFilter( containerComponent.getUniqueId(),entry.getKey(),entry.getValue()); if (renameEither.isRight()){ return Either.right(componentsUtils.getResponseFormatForResourceInstance( @@ -1051,86 +1060,99 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return oldComponentInstance; } - public ComponentInstance deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) { + public ComponentInstance deleteComponentInstance(final String containerComponentParam, + final String containerComponentId, + final String componentInstanceId, String userId) + throws BusinessLogicException { validateUserExists(userId); - final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam); - org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); + final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null); validateCanWorkOnComponent(containerComponent, userId); boolean failed = false; - ComponentInstance deletedRelatedInst; + final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId); + if (!componentInstanceOptional.isPresent()) { + throw new BusinessLogicException(componentsUtils + .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND)); + } + ComponentInstance componentInstance = componentInstanceOptional.get(); + try { - if (containerComponent instanceof Service) { - ComponentInstance componentInstance = containerComponent.getComponentInstanceById(componentInstanceId).get(); - Either<String, StorageOperationStatus> deleteServiceFilterEither = - serviceFilterOperation.deleteNodeFilter((Service) containerComponent, componentInstanceId); + if (containerComponent instanceof Service || containerComponent instanceof Resource && + isVFC(componentInstance.getOriginType())) { + + final Either<String, StorageOperationStatus> deleteServiceFilterEither = + nodeFilterOperation.deleteNodeFilter(containerComponent, componentInstanceId); if (deleteServiceFilterEither.isRight()) { - ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(), + final ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType); janusGraphDao.rollback(); throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId)); } - Either<ComponentInstance, ResponseFormat> resultOp = deleteServiceFiltersRelatedTobeDeletedComponentInstance((Service) containerComponent, - componentInstance, ComponentTypeEnum.SERVICE, userId); + final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance( + containerComponent, componentInstance, containerComponentType, userId); if (resultOp.isRight()) { janusGraphDao.rollback(); throw new ByResponseFormatComponentException(resultOp.right().value()); } } lockComponent(containerComponent, "deleteComponentInstance"); - ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); + final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType); - deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, + componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType, deletedCompInstance); - ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId); + final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId); if (ActionStatus.OK != onDeleteOperationsStatus) { throw new ByActionStatusComponentException(onDeleteOperationsStatus); } - } catch (ComponentException e) { + } catch (final ComponentException e) { failed = true; throw e; } finally { unlockComponent(failed, containerComponent); } - return deletedRelatedInst; - } - - public Either<ComponentInstance, ResponseFormat> deleteServiceFiltersRelatedTobeDeletedComponentInstance( - Service service, ComponentInstance componentInstance, ComponentTypeEnum containerComponentType, String userId) { - if (containerComponentType.equals(ComponentTypeEnum.SERVICE)) { - Set<String> serviceFiltersIDsToBeDeleted = - getServiceFiltersRelatedToComponentInstance(service.getUniqueId(), componentInstance); - if (!serviceFiltersIDsToBeDeleted.isEmpty()) { - Set<String> ids = service.getComponentInstances().stream() - .filter(ci -> serviceFiltersIDsToBeDeleted - .contains(ci.getName())) - .map(ComponentInstance::getUniqueId) - .collect(Collectors.toSet()); - Either<Set<String>, StorageOperationStatus> deleteServiceFiltersEither = - serviceFilterOperation.deleteNodeFilters(service, ids); - if (deleteServiceFiltersEither.isRight()) { - ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFiltersEither.right().value(), - containerComponentType); - return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName())); + return componentInstance; + } + + public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance( + final Component component, + final ComponentInstance componentInstance, + final ComponentTypeEnum containerComponentType, + final String userId) { + + final Set<String> componentFiltersIDsToBeDeleted = + getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance); + if (!componentFiltersIDsToBeDeleted.isEmpty()) { + final Set<String> ids = component.getComponentInstances().stream() + .filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName())) + .map(ComponentInstance::getUniqueId).collect(Collectors.toSet()); + final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither = + nodeFilterOperation.deleteNodeFilters(component, ids); + if (deleteComponentNodeFiltersEither.isRight()) { + final ActionStatus status = componentsUtils + .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), + containerComponentType); + return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName())); + } + for (final String id : ids) { + final Optional<ComponentInstance> componentInstanceById = component.getComponentInstanceById(id); + if (!componentInstanceById.isPresent()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); } - for (String id : ids) { - final Optional<ComponentInstance> componentInstanceById = service.getComponentInstanceById(id); - if (!componentInstanceById.isPresent()){ - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - ComponentInstance ci = componentInstanceById.get(); - ci.setDirectives(Collections.emptyList()); - - final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = - updateComponentInstanceMetadata(ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUniqueId(), - ci.getUniqueId(), userId, ci, true, false); - if (componentInstanceResponseFormatEither.isRight()) { - return componentInstanceResponseFormatEither; - } + final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get(); + final List<String> directives = componentInstanceToBeUpdated.getDirectives(); + if (CollectionUtils.isNotEmpty(directives)) { + directives.removeAll(directives); + componentInstanceToBeUpdated.setDirectives(Collections.emptyList()); + } + final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = + updateComponentInstanceMetadata(containerComponentType.getValue(), component.getUniqueId(), + componentInstanceToBeUpdated.getUniqueId(), userId, componentInstanceToBeUpdated, true, false); + if (componentInstanceResponseFormatEither.isRight()) { + return componentInstanceResponseFormatEither; } } } @@ -1139,14 +1161,14 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { - private Set<String> getServiceFiltersRelatedToComponentInstance(String containerComponentId, - ComponentInstance componentInstance) { + private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId, + ComponentInstance componentInstance) { ComponentParametersView filter = new ComponentParametersView(true); filter.setIgnoreComponentInstances(false); - Either<Service, StorageOperationStatus> serviceFilterOrigin = + Either<Component, StorageOperationStatus> componentFilterOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter); - final Service service = serviceFilterOrigin.left().value(); - final Set<String> nodesFiltersToBeDeleted = ServiceFilterUtils.getNodesFiltersToBeDeleted(service, + final Component component = componentFilterOrigin.left().value(); + final Set<String> nodesFiltersToBeDeleted = ComponentsUtils.getNodesFiltersToBeDeleted(component, componentInstance); return nodesFiltersToBeDeleted; } @@ -1163,10 +1185,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { return componentInstance; } - - - - private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){ Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); @@ -2624,107 +2642,6 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { } } - /*private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance, - String capabilityType, String capabilityName, String ownerId) { - String componentInstanceUniqueId = foundResourceInstance.getUniqueId(); - Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities()) - .orElse(Collections.emptyMap()); - List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList()); - Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny(); - if (cap.isPresent()) { - List<ComponentInstanceProperty> capProperties = cap.get().getProperties(); - if (capProperties != null) { - Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny(); - StorageOperationStatus status; - if (instanceProperty.isPresent()) { - String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get()); - instanceProperty.get().setValue(newValue); - List<String> path = new ArrayList<>(); - path.add(componentInstanceUniqueId); - path.add(capKey); - instanceProperty.get().setPath(path); - status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get()); - if (status != StorageOperationStatus.OK) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status); - return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""); - - } - foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString()); - } - } - } - return componentsUtils.getResponseFormat(ActionStatus.OK); - }*/ - - /*public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, - List<ComponentInstanceProperty> properties, String userId) { - Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; - - validateUserExists(userId); - - if (componentTypeEnum == null) { - BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED)); - } - Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId); - - if (getResourceResult.isRight()) { - log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - Component containerComponent = getResourceResult.left().value(); - - if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) { - log.info("Restricted operation for user: {} on component {}", userId, containerComponentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); - } - Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId); - if (resourceInstanceStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId)); - } - ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value(); - // lock resource - StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType()); - if (lockStatus != StorageOperationStatus.OK) { - log.debug("Failed to lock component {}", containerComponentId); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus))); - } - - Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll(); - if (allDataTypes.isRight()) { - JanusGraphOperationStatus status = allDataTypes.right().value(); - BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status)))); - } - - try { - for (ComponentInstanceProperty property : properties) { - Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, false); - newPropertyValueEither.bimap(updatedValue -> - updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId), - Either::right); - } - Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent); - - if (updateContainerRes.isRight()) { - ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value()); - resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "")); - return resultOp; - } - resultOp = Either.left(properties); - return resultOp; - - } finally { - if (resultOp == null || resultOp.isRight()) { - janusGraphDao.rollback(); - } else { - janusGraphDao.commit(); - } - // unlock resource - graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType()); - } - }*/ - public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, List<ComponentInstanceProperty> properties, String userId) { Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null; @@ -3227,8 +3144,15 @@ public class ComponentInstanceBusinessLogic extends BaseBusinessLogic { log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId); return Either.right(new ResponseFormat()); } + } + public boolean isVFC(final OriginTypeEnum originTypeEnum) { + return OriginTypeEnum.VFC.equals(originTypeEnum); + } + public void validateUser(final String userId) { + final User user = userValidations.validateUserExists(userId); + userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN)); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java new file mode 100644 index 0000000000..0356b63793 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ComponentNodeFilterBusinessLogic.java @@ -0,0 +1,417 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.components.impl; + +import static org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR; + +import fj.data.Either; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException; +import org.openecomp.sdc.be.components.impl.utils.NodeFilterConstraintAction; +import org.openecomp.sdc.be.components.validation.NodeFilterValidator; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; +import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterPropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; +import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation; +import org.openecomp.sdc.be.model.operations.api.IElementOperation; +import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; +import org.openecomp.sdc.be.model.operations.api.IGroupOperation; +import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation; +import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; +import org.openecomp.sdc.be.user.Role; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.exception.ResponseFormat; +import org.springframework.beans.factory.annotation.Autowired; + +@org.springframework.stereotype.Component("componentNodeFilterBusinessLogic") +public class ComponentNodeFilterBusinessLogic extends BaseBusinessLogic { + + private static final Logger LOGGER = Logger.getLogger(ComponentNodeFilterBusinessLogic.class.getName()); + + private final NodeFilterOperation nodeFilterOperation; + private final NodeFilterValidator nodeFilterValidator; + + @Autowired + public ComponentNodeFilterBusinessLogic(final IElementOperation elementDao, + final IGroupOperation groupOperation, + final IGroupInstanceOperation groupInstanceOperation, + final IGroupTypeOperation groupTypeOperation, + final InterfaceOperation interfaceOperation, + final InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + final ArtifactsOperations artifactToscaOperation, + final NodeFilterOperation nodeFilterOperation, + final NodeFilterValidator nodeFilterValidator) { + super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, + interfaceLifecycleTypeOperation, artifactToscaOperation); + this.nodeFilterOperation = nodeFilterOperation; + this.nodeFilterValidator = nodeFilterValidator; + } + + public Optional<CINodeFilterDataDefinition> createNodeFilterIfNotExist(final String componentId, + final String componentInstanceId, + final boolean shouldLock, + final ComponentTypeEnum componentTypeEnum) + throws BusinessLogicException { + + final Component component = getComponent(componentId); + final Optional<ComponentInstance> componentInstance = getComponentInstance(componentInstanceId, component); + Optional<CINodeFilterDataDefinition> filterDataDefinition = getCiNodeFilterDataDefinition(componentInstance); + if (filterDataDefinition.isPresent()) { + return filterDataDefinition; + } + final Either<CINodeFilterDataDefinition, StorageOperationStatus> result; + boolean wasLocked = false; + try { + if (shouldLock) { + lockComponent(component.getUniqueId(), component,"Create Node Filter on component"); + wasLocked = true; + } + result = nodeFilterOperation.createNodeFilter(componentId, componentInstanceId); + if (result.isRight()) { + janusGraphDao.rollback(); + LOGGER.error(BUSINESS_PROCESS_ERROR, + "Failed to Create Node filter on component with id {}", componentId); + throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils + .convertFromStorageResponse(result.right().value()), component.getSystemName())); + } else { + filterDataDefinition = Optional.ofNullable(result.left().value()); + } + janusGraphDao.commit(); + LOGGER.debug("Node filter successfully created in component {} . ", component.getSystemName()); + + } catch (final Exception e) { + janusGraphDao.rollback(); + LOGGER.error(BUSINESS_PROCESS_ERROR, + "Exception occurred during add Component node filter property values: {}", e.getMessage(), e); + throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } finally { + if (wasLocked) { + unlockComponent(component.getUniqueId(), componentTypeEnum); + } + } + return filterDataDefinition; + } + + public Optional<String> deleteNodeFilterIfExists(final String componentId, + final String componentInstanceId, + final boolean shouldLock, + final ComponentTypeEnum componentTypeEnum) + throws BusinessLogicException { + + final Component component = getComponent(componentId); + final Optional<CINodeFilterDataDefinition> nodeFilterDataDefinition = + getCiNodeFilterDataDefinition(componentInstanceId, component); + if (!nodeFilterDataDefinition.isPresent()) { + return Optional.ofNullable(componentInstanceId); + } + + final Either<String, StorageOperationStatus> result; + boolean wasLocked = false; + try { + if (shouldLock) { + lockComponent(component.getUniqueId(), component,"Delete Node Filter from component"); + wasLocked = true; + } + result = nodeFilterOperation.deleteNodeFilter(component, componentInstanceId); + if (result.isRight()) { + LOGGER.error(BUSINESS_PROCESS_ERROR, + "Failed to delete node filter in component {}. Response is {}. ", component.getName(), + result.right().value()); + janusGraphDao.rollback(); + throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils + .convertFromStorageResponse(result.right().value()), component.getSystemName())); + } + janusGraphDao.commit(); + LOGGER.debug("Node filter successfully deleted in component {} . ", component.getSystemName()); + + } catch (final Exception e) { + LOGGER.error(BUSINESS_PROCESS_ERROR,"Exception occurred during delete deleting node filter: {}", + e.getMessage(), e); + janusGraphDao.rollback(); + throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + } finally { + if (wasLocked) { + unlockComponent(component.getUniqueId(), componentTypeEnum); + } + } + return Optional.ofNullable(result.left().value()); + } + + + + public Optional<CINodeFilterDataDefinition> addNodeFilter(final String componentId, + final String componentInstanceId, + final NodeFilterConstraintAction action, + final String propertyName, + final String constraint, + final boolean shouldLock, + final ComponentTypeEnum componentTypeEnum) + throws BusinessLogicException { + + final Component component = getComponent(componentId); + CINodeFilterDataDefinition nodeFilterDataDefinition = validateAndReturnNodeFilterDefinition(componentInstanceId, + action, constraint, component); + boolean wasLocked = false; + try { + if (shouldLock) { + lockComponent(component.getUniqueId(), component,"Add Node Filter on Component"); + wasLocked = true; + } + final RequirementNodeFilterPropertyDataDefinition newProperty = + new RequirementNodeFilterPropertyDataDefinition(); + newProperty.setName(propertyName); + newProperty.setConstraints(Collections.singletonList(constraint)); + final Either<CINodeFilterDataDefinition, StorageOperationStatus> result = nodeFilterOperation + .addNewProperty(componentId, componentInstanceId, nodeFilterDataDefinition, newProperty); + + if (result.isRight()) { + janusGraphDao.rollback(); + throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils + .convertFromStorageResponse(result.right().value()), component.getSystemName())); + } else { + nodeFilterDataDefinition = result.left().value(); + } + janusGraphDao.commit(); + LOGGER.debug("Node filter successfully created in component {} . ", component.getSystemName()); + + } catch (final Exception e) { + janusGraphDao.rollback(); + LOGGER.error(BUSINESS_PROCESS_ERROR, + "Exception occurred during add component node filter property values: {}", e.getMessage(), e); + throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } finally { + if (wasLocked) { + unlockComponent(component.getUniqueId(), componentTypeEnum); + } + } + return Optional.ofNullable(nodeFilterDataDefinition); + } + + public Optional<CINodeFilterDataDefinition> deleteNodeFilter(final String componentId, + final String componentInstanceId, + final NodeFilterConstraintAction action, + final String constraint, + final int position, + final boolean shouldLock, + final ComponentTypeEnum componentTypeEnum) + throws BusinessLogicException { + + final Component component = getComponent(componentId); + CINodeFilterDataDefinition nodeFilterDataDefinition = + validateAndReturnNodeFilterDefinition(componentInstanceId, action, constraint, component); + boolean wasLocked = false; + try { + if (shouldLock) { + lockComponent(component.getUniqueId(), component,"Add Node Filter on Component"); + wasLocked = true; + } + final Either<CINodeFilterDataDefinition, StorageOperationStatus> result = nodeFilterOperation + .deleteConstraint(componentId, componentInstanceId, nodeFilterDataDefinition, position); + if (result.isRight()) { + janusGraphDao.rollback(); + throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils + .convertFromStorageResponse(result.right().value()), component.getSystemName())); + } else { + nodeFilterDataDefinition = result.left().value(); + } + janusGraphDao.commit(); + LOGGER.debug("Node filter successfully deleted in component {} . ", component.getSystemName()); + + } catch (final Exception e) { + janusGraphDao.rollback(); + LOGGER.error(BUSINESS_PROCESS_ERROR, + "Exception occurred during delete component node filter property values: {}", e.getMessage(), e); + throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } finally { + if (wasLocked) { + unlockComponent(component.getUniqueId(), componentTypeEnum); + } + } + return Optional.ofNullable(nodeFilterDataDefinition); + } + + public Optional<CINodeFilterDataDefinition> updateNodeFilter(final String componentId, + final String componentInstanceId, + final List<String> constraints, + final boolean shouldLock, + final ComponentTypeEnum componentTypeEnum) + throws BusinessLogicException { + + final Component component = getComponent(componentId); + + final Either<Boolean, ResponseFormat> response = nodeFilterValidator + .validateNodeFilter(component, componentInstanceId, constraints, NodeFilterConstraintAction.UPDATE); + if (response.isRight()) { + throw new BusinessLogicException(componentsUtils + .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); + } + boolean wasLocked = false; + if (shouldLock) { + lockComponent(component.getUniqueId(), component,"Update Node Filter on Component"); + wasLocked = true; + } + final Optional<ComponentInstance> componentInstance = getComponentInstance(componentInstanceId, + component); + if (!componentInstance.isPresent()) { + throw new BusinessLogicException(ResponseFormatManager.getInstance() + .getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + CINodeFilterDataDefinition nodeFilterDataDefinition = componentInstance.get().getNodeFilter(); + if (nodeFilterDataDefinition == null) { + throw new BusinessLogicException(componentsUtils + .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); + } + try { + final List<RequirementNodeFilterPropertyDataDefinition> properties = constraints.stream() + .map(this::getRequirementNodeFilterPropertyDataDefinition).collect(Collectors.toList()); + final Either<CINodeFilterDataDefinition, StorageOperationStatus> result = nodeFilterOperation + .updateProperties(componentId, componentInstanceId, nodeFilterDataDefinition, properties); + + if (result.isRight()) { + janusGraphDao.rollback(); + throw new BusinessLogicException(componentsUtils.getResponseFormatByResource(componentsUtils + .convertFromStorageResponse(result.right().value()), component.getSystemName())); + } else { + nodeFilterDataDefinition = result.left().value(); + } + janusGraphDao.commit(); + LOGGER.debug("Node filter successfully updated in component {} . ", component.getSystemName()); + + } catch (final Exception e) { + janusGraphDao.rollback(); + LOGGER.error(BUSINESS_PROCESS_ERROR, + "Exception occurred during update component node filter property values: {}", + e.getMessage(), e); + throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } finally { + if (wasLocked) { + unlockComponent(component.getUniqueId(), componentTypeEnum); + } + } + return Optional.ofNullable(nodeFilterDataDefinition); + } + + private void unlockComponent(final String componentUniqueId, + final ComponentTypeEnum componentType) { + graphLockOperation.unlockComponent(componentUniqueId, componentType.getNodeType()); + } + + public User validateUser(final String userId) { + final User user = userValidations.validateUserExists(userId); + userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN)); + return user; + } + + private Component getComponent(final String componentId) throws BusinessLogicException { + + final Either<Component, StorageOperationStatus> result = + toscaOperationFacade.getToscaElement(componentId); + + if (result.isRight()) { + final StorageOperationStatus errorStatus = result.right().value(); + LOGGER.error(BUSINESS_PROCESS_ERROR, this.getClass().getName(), + "Failed to fetch component information by component id, error {}", errorStatus); + throw new BusinessLogicException(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(errorStatus))); + } + return result.left().value(); + } + + private Optional<ComponentInstance> getComponentInstance(final String componentInstanceId, + final Component component) { + return component.getComponentInstanceById(componentInstanceId); + } + + private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition( + final Optional<ComponentInstance> componentInstance) { + + if (componentInstance.isPresent()) { + return Optional.ofNullable(componentInstance.get().getNodeFilter()); + } + return Optional.empty(); + } + + private Optional<CINodeFilterDataDefinition> getCiNodeFilterDataDefinition(final String componentInstanceId, + final Component component) + throws BusinessLogicException { + + final Either<Boolean, ResponseFormat> response = nodeFilterValidator + .validateComponentInstanceExist(component, componentInstanceId); + if (response.isRight()) { + throw new BusinessLogicException(componentsUtils + .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); + } + final Optional<ComponentInstance> componentInstance = getComponentInstance(componentInstanceId, component); + if (componentInstance.isPresent()) { + return Optional.ofNullable(componentInstance.get().getNodeFilter()); + } + return Optional.empty(); + } + + private RequirementNodeFilterPropertyDataDefinition getRequirementNodeFilterPropertyDataDefinition( + final String constraint) { + + final RequirementNodeFilterPropertyDataDefinition pdd = new RequirementNodeFilterPropertyDataDefinition(); + pdd.setConstraints(Arrays.asList(constraint)); + return pdd; + } + + private CINodeFilterDataDefinition validateAndReturnNodeFilterDefinition(final String componentInstanceId, + final NodeFilterConstraintAction action, + final String constraint, + final Component component) + throws BusinessLogicException { + + validateNodeFilter(component, componentInstanceId, action, constraint); + final Optional<CINodeFilterDataDefinition> cINodeFilterDataDefinition = getCiNodeFilterDataDefinition( + componentInstanceId, component); + if (!cINodeFilterDataDefinition.isPresent()) { + throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); + } + return cINodeFilterDataDefinition.get(); + } + + private void validateNodeFilter(final Component component, + final String componentInstanceId, + final NodeFilterConstraintAction action, + final String constraint) throws BusinessLogicException { + final Either<Boolean, ResponseFormat> response = nodeFilterValidator + .validateNodeFilter(component, componentInstanceId, Collections.singletonList(constraint), action); + if (response.isRight()) { + throw new BusinessLogicException(componentsUtils + .getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND, response.right().value().getFormattedMessage())); + } + } +}
\ No newline at end of file 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 bdcc67c744..f4ccb868d9 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 @@ -22,12 +22,38 @@ package org.openecomp.sdc.be.components.impl; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.openecomp.sdc.be.components.utils.ConsumptionUtils.handleConsumptionInputMappedToCapabilityProperty; +import static org.openecomp.sdc.be.components.utils.ConsumptionUtils.isAssignedValueFromValidType; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationOutputName; +import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToOtherOperationOutput; +import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_SERVICE_METADATA; +import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF; +import static org.openecomp.sdc.be.types.ServiceConsumptionSource.SERVICE_INPUT; +import static org.openecomp.sdc.be.types.ServiceConsumptionSource.STATIC; + import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fj.data.Either; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.stream.Collectors; +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.collections4.ListUtils; @@ -41,12 +67,10 @@ import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; -import org.openecomp.sdc.be.components.impl.utils.NodeFilterConstraintAction; import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction; import org.openecomp.sdc.be.components.path.ForwardingPathValidator; import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils; import org.openecomp.sdc.be.components.utils.PropertiesUtils; -import org.openecomp.sdc.be.components.validation.NodeFilterValidator; import org.openecomp.sdc.be.components.validation.ServiceDistributionValidation; import org.openecomp.sdc.be.components.validation.component.ComponentContactIdValidator; import org.openecomp.sdc.be.components.validation.component.ComponentDescriptionValidator; @@ -69,13 +93,11 @@ import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.datamodel.ServiceRelations; import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil; import org.openecomp.sdc.be.datamodel.utils.UiComponentDataConverter; -import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition; import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationOutputDefinition; -import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterPropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentFieldsEnum; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; @@ -107,7 +129,6 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation; -import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation; import org.openecomp.sdc.be.model.operations.api.IElementOperation; import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation; import org.openecomp.sdc.be.model.operations.api.IGroupOperation; @@ -117,7 +138,6 @@ import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils; import org.openecomp.sdc.be.plugins.ServiceCreationPlugin; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.be.resources.data.ComponentInstanceData; import org.openecomp.sdc.be.resources.data.ComponentMetadataData; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; @@ -136,43 +156,16 @@ import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.Wrapper; import org.openecomp.sdc.common.kpi.api.ASDCKpiApi; -import org.openecomp.sdc.common.log.elements.LoggerSupportability; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.util.GeneralUtility; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.openecomp.sdc.common.util.ValidationUtils; import org.openecomp.sdc.exception.ResponseFormat; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.context.WebApplicationContext; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.function.Function; -import java.util.stream.Collectors; - -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.openecomp.sdc.be.components.utils.ConsumptionUtils.handleConsumptionInputMappedToCapabilityProperty; -import static org.openecomp.sdc.be.components.utils.ConsumptionUtils.isAssignedValueFromValidType; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.getOperationOutputName; -import static org.openecomp.sdc.be.components.utils.InterfaceOperationUtils.isOperationInputMappedToOtherOperationOutput; -import static org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum.UPDATE_SERVICE_METADATA; -import static org.openecomp.sdc.be.tosca.InterfacesOperationsConverter.SELF; -import static org.openecomp.sdc.be.types.ServiceConsumptionSource.SERVICE_INPUT; -import static org.openecomp.sdc.be.types.ServiceConsumptionSource.STATIC; - @org.springframework.stereotype.Component("serviceBusinessLogic") public class ServiceBusinessLogic extends ComponentBusinessLogic { @@ -185,7 +178,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private static final String INITIAL_VERSION = "0.1"; private static final String STATUS_SUCCESS_200 = "200"; private static final String STATUS_DEPLOYED = "DEPLOYED"; - private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(ServiceBusinessLogic.class.getName()); static final String IS_VALID = "isValid"; private ForwardingPathOperation forwardingPathOperation; @@ -196,8 +188,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private final ServiceDistributionValidation serviceDistributionValidation; private final ForwardingPathValidator forwardingPathValidator; private final UiComponentDataConverter uiComponentDataConverter; - private final NodeFilterOperation serviceFilterOperation; - private final NodeFilterValidator serviceFilterValidator; private ServiceTypeValidator serviceTypeValidator; private List<ServiceCreationPlugin> serviceCreationPluginList; @@ -230,24 +220,24 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { @Autowired public ServiceBusinessLogic(IElementOperation elementDao, - IGroupOperation groupOperation, - IGroupInstanceOperation groupInstanceOperation, - IGroupTypeOperation groupTypeOperation, - GroupBusinessLogic groupBusinessLogic, - InterfaceOperation interfaceOperation, - InterfaceLifecycleOperation interfaceLifecycleTypeOperation, - ArtifactsBusinessLogic artifactsBusinessLogic, - IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, - ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator, - UiComponentDataConverter uiComponentDataConverter, NodeFilterOperation serviceFilterOperation, - NodeFilterValidator serviceFilterValidator, ArtifactsOperations artifactToscaOperation, - ComponentContactIdValidator componentContactIdValidator, - ComponentNameValidator componentNameValidator, - ComponentTagsValidator componentTagsValidator, - ComponentValidator componentValidator, - ComponentIconValidator componentIconValidator, - ComponentProjectCodeValidator componentProjectCodeValidator, - ComponentDescriptionValidator componentDescriptionValidator) { + IGroupOperation groupOperation, + IGroupInstanceOperation groupInstanceOperation, + IGroupTypeOperation groupTypeOperation, + GroupBusinessLogic groupBusinessLogic, + InterfaceOperation interfaceOperation, + InterfaceLifecycleOperation interfaceLifecycleTypeOperation, + ArtifactsBusinessLogic artifactsBusinessLogic, + IDistributionEngine distributionEngine, ComponentInstanceBusinessLogic componentInstanceBusinessLogic, + ServiceDistributionValidation serviceDistributionValidation, ForwardingPathValidator forwardingPathValidator, + UiComponentDataConverter uiComponentDataConverter, + ArtifactsOperations artifactToscaOperation, + ComponentContactIdValidator componentContactIdValidator, + ComponentNameValidator componentNameValidator, + ComponentTagsValidator componentTagsValidator, + ComponentValidator componentValidator, + ComponentIconValidator componentIconValidator, + ComponentProjectCodeValidator componentProjectCodeValidator, + ComponentDescriptionValidator componentDescriptionValidator) { super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, groupBusinessLogic, interfaceOperation, interfaceLifecycleTypeOperation, artifactsBusinessLogic, artifactToscaOperation, componentContactIdValidator, componentNameValidator, componentTagsValidator, componentValidator, @@ -257,9 +247,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { this.serviceDistributionValidation = serviceDistributionValidation; this.forwardingPathValidator = forwardingPathValidator; this.uiComponentDataConverter = uiComponentDataConverter; - this.serviceFilterOperation = serviceFilterOperation; - this.serviceFilterValidator = serviceFilterValidator; - } @@ -1239,7 +1226,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { private void validateUserAndRole(Service serviceUpdate, User user, String errorContext) { user = validateUser(user, errorContext, serviceUpdate, null, false); validateUserRole(user, serviceUpdate, new ArrayList<>(), null, null); - } @VisibleForTesting @@ -2509,252 +2495,6 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { return Either.left(dataTransfer); } - public Either<String, ResponseFormat> deleteIfNotAlreadyDeletedServiceFilter(String serviceId, String resourceId, String userId, boolean lock) { - validateUserExists(userId); - - Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId); - if (storageStatus.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE), "")); - } - Service service = storageStatus.left().value(); - - Either<Boolean, ResponseFormat> response = serviceFilterValidator.validateComponentInstanceExist(service, resourceId); - if (storageStatus.isRight()) { - return Either.right(response.right().value()); - } - final Optional<ComponentInstance> optionalComponentInstance = service.getComponentInstanceById(resourceId); - if (!optionalComponentInstance.isPresent() ){ - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - CINodeFilterDataDefinition nodeFilter = optionalComponentInstance.get().getNodeFilter(); - if (nodeFilter == null){ - return Either.left(resourceId); - } - - Either<String, StorageOperationStatus> result; - try{ - if (lock) { - lockComponent(service.getUniqueId(), service, "Delete Service Filter from service"); - } - result = serviceFilterOperation.deleteNodeFilter(service , resourceId); - if (result.isRight()) { - log.debug("Failed to delete node filter in service {}. Response is {}. ", service.getName(), result.right().value()); - janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus.right().value(), ComponentTypeEnum.SERVICE))); - } - janusGraphDao.commit(); - log.debug("Node filter successfully changed in service {} . ", service.getSystemName()); - - } catch (Exception e){ - log.error("Exception occurred during delete forwarding path : {}", e.getMessage(), e); - janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } finally { - graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); - } - return Either.left(result.left().value()); - } - - - public Either<CINodeFilterDataDefinition, ResponseFormat> createIfNotAlreadyExistServiceFilter(String serviceId, String componentInstanceId, String userId, boolean lock) { - String errorContext = "createIfNotAlreadyExistServiceFilter"; - User user = validateUserExists(userId); - - Either<Service, StorageOperationStatus> serviceEither = toscaOperationFacade.getToscaElement(serviceId); - if (serviceEither.isRight()) { - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceEither.right().value(), ComponentTypeEnum.SERVICE), "")); - } - final Service service = serviceEither.left().value(); - validateUserAndRole(service, user, errorContext); - - Optional<ComponentInstance> optionalComponentInstance = service.getComponentInstanceById(componentInstanceId); - if (!optionalComponentInstance.isPresent()){ - return Either.right(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); - } - ComponentInstance componentInstance = optionalComponentInstance.get(); - CINodeFilterDataDefinition serviceFilter = componentInstance.getNodeFilter(); - if (serviceFilter != null){ - return Either.left(serviceFilter); - } - if (lock) { - lockComponent(service.getUniqueId(), service, "Create Service Filter"); - } - Either<CINodeFilterDataDefinition, StorageOperationStatus> result; - - CINodeFilterDataDefinition serviceFilterResult; - try { - result = serviceFilterOperation.createNodeFilter(serviceId, componentInstanceId); - if (result.isRight()) { - janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), - "")); - } else { - serviceFilterResult = result.left().value(); - } - janusGraphDao.commit(); - - } catch (Exception e) { - janusGraphDao.rollback(); - log.error("Exception occurred during add or update service filter property values: {}", e.getMessage(), - e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } finally { - graphLockOperation.unlockComponent(service.getUniqueId(), NodeTypeEnum.Service); - } - return Either.left(serviceFilterResult); - } - - - public Either<CINodeFilterDataDefinition, ResponseFormat> updateServiceFilter(String serviceId, String componentInstanceId, - List<String> constraints, User inUser, boolean lock) { - User user = validateUserExists(inUser.getUserId()); - validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN)); - Either<Service, StorageOperationStatus> serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId); - - if(serviceStorageOperationStatusEither.isRight()){ - StorageOperationStatus errorStatus = serviceStorageOperationStatusEither.right().value(); - log.debug("Failed to fetch service information by service id, error {}", errorStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); - } - Service storedService = serviceStorageOperationStatusEither.left().value(); - - Either<Boolean, ResponseFormat> booleanResponseFormatEither = - serviceFilterValidator.validateNodeFilter(storedService, componentInstanceId, constraints, - NodeFilterConstraintAction.UPDATE); - if(booleanResponseFormatEither.isRight()){ - return Either.right(booleanResponseFormatEither.right().value()); - } - - - Either<Boolean, ResponseFormat> lockResult = null; - if (lock) { - lockComponent(storedService.getUniqueId(), storedService, "Add or Update Service Filter on Service"); - } - Optional<ComponentInstance> componentInstanceOptional = storedService.getComponentInstanceById(componentInstanceId); - if (!componentInstanceOptional.isPresent()){ - return Either.right(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); - } - CINodeFilterDataDefinition serviceFilter = componentInstanceOptional.get().getNodeFilter(); - if(serviceFilter == null){ - return Either.right(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); - } - CINodeFilterDataDefinition serviceFilterResult; - try { - List<RequirementNodeFilterPropertyDataDefinition> properties = constraints.stream().map(this::getRequirementNodeFilterPropertyDataDefinition).collect(Collectors.toList()); - Either<CINodeFilterDataDefinition, StorageOperationStatus> result = serviceFilterOperation.updateProperties(serviceId, componentInstanceId, serviceFilter ,properties); - - if (result.isRight()) { - janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), - "")); - } else { - serviceFilterResult = result.left().value(); - } - janusGraphDao.commit(); - - } catch (Exception e) { - janusGraphDao.rollback(); - log.error("Exception occurred during add or update service filter property values: {}", e.getMessage(), - e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } finally { - if (lockResult != null && lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedService.getUniqueId(), NodeTypeEnum.Service); - } - } - return Either.left(serviceFilterResult); - } - - private RequirementNodeFilterPropertyDataDefinition getRequirementNodeFilterPropertyDataDefinition(String constraint){ - RequirementNodeFilterPropertyDataDefinition pdd = new RequirementNodeFilterPropertyDataDefinition(); - pdd.setConstraints(Arrays.asList(constraint)); - return pdd; - } - - public Either<CINodeFilterDataDefinition, ResponseFormat> addOrDeleteServiceFilter(String serviceId, String componentInstanceId, - NodeFilterConstraintAction action, String propertyName, String constraint, int position, User inUser, boolean lock) { - User user = validateUserExists(inUser.getUserId()); - validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN)); - - Either<Service, StorageOperationStatus> serviceStorageOperationStatusEither = toscaOperationFacade.getToscaElement(serviceId); - - if(serviceStorageOperationStatusEither.isRight()){ - StorageOperationStatus errorStatus = serviceStorageOperationStatusEither.right().value(); - log.debug("Failed to fetch service information by service id, error {}", errorStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); - } - Service storedService = serviceStorageOperationStatusEither.left().value(); - - Either<Boolean, ResponseFormat> booleanResponseFormatEither = - serviceFilterValidator.validateNodeFilter(storedService, componentInstanceId, - Collections.singletonList(constraint), action); - if(booleanResponseFormatEither.isRight()){ - return Either.right(booleanResponseFormatEither.right().value()); - } - - Either<CINodeFilterDataDefinition, StorageOperationStatus> result = null; - - CINodeFilterDataDefinition serviceFilterResult = null; - ActionStatus lockStatus = null; - try { - if (lock) { - lockStatus = lockComponentAndReturnStatus(storedService.getUniqueId(), storedService, "Add or Update Service Filter on Service"); - } - - Optional<ComponentInstance> componentInstanceOptional = storedService.getComponentInstanceById(componentInstanceId); - if (!componentInstanceOptional.isPresent()) { - return Either.right(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); - } - CINodeFilterDataDefinition serviceFilter = componentInstanceOptional.get().getNodeFilter(); - if (serviceFilter == null) { - return Either.right(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.NODE_FILTER_NOT_FOUND)); - } - - - switch (action) { - case ADD: - RequirementNodeFilterPropertyDataDefinition newProperty = new RequirementNodeFilterPropertyDataDefinition(); - newProperty.setName(propertyName); - newProperty.setConstraints(Collections.singletonList(constraint)); - result = serviceFilterOperation.addNewProperty(serviceId, componentInstanceId, serviceFilter, newProperty); - break; - case DELETE: - result = serviceFilterOperation.deleteConstraint(serviceId, componentInstanceId, serviceFilter, position); - break; - default: - log.error("Unsupported operation " + action); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } - - if (result != null && result.isRight()) { - janusGraphDao.rollback(); - return Either.right(componentsUtils.getResponseFormat( - componentsUtils.convertFromStorageResponse(result.right().value(), ComponentTypeEnum.SERVICE), - "")); - } else { - serviceFilterResult = result.left().value(); - } - janusGraphDao.commit(); - - } catch (Exception e) { - janusGraphDao.rollback(); - log.error("Exception occurred during add or update node filter property values: {}", e.getMessage(), - e); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - - } finally { - if (ActionStatus.OK == lockStatus) { - graphLockOperation.unlockComponent(storedService.getUniqueId(), NodeTypeEnum.Service); - } - } - return Either.left(serviceFilterResult); - } - @Autowired(required = false) public void setServiceCreationPluginList(List<ServiceCreationPlugin> serviceCreationPluginList) { this.serviceCreationPluginList = serviceCreationPluginList; diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java index 021e6b49e4..3c770d15aa 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/NodeFilterValidator.java @@ -22,18 +22,23 @@ package org.openecomp.sdc.be.components.validation; import com.google.common.collect.ImmutableSet; 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.Set; import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.components.impl.utils.NodeFilterConstraintAction; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.datamodel.utils.ConstraintConvertor; -import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition; 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.PropertyDefinition; -import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.tosca.ToscaPropertyType; import org.openecomp.sdc.be.ui.model.UIConstraint; @@ -41,17 +46,9 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -@Component("NodeFilterValidator") +@org.springframework.stereotype.Component("NodeFilterValidator") public class NodeFilterValidator { private static final String SOURCE = "Source"; @@ -70,18 +67,19 @@ public class NodeFilterValidator { private static final Logger LOGGER = LoggerFactory.getLogger(NodeFilterValidator.class); - public Either<Boolean, ResponseFormat> validateComponentInstanceExist(Service service, String componentInstanceId) { - if (service == null || StringUtils.isEmpty(componentInstanceId)) { + public Either<Boolean, ResponseFormat> validateComponentInstanceExist( + final Component component, + final String componentInstanceId) { + if (component == null || StringUtils.isEmpty(componentInstanceId)) { LOGGER.debug("Input data cannot be empty"); return getErrorResponse(ActionStatus.NODE_FILTER_NOT_FOUND); } - if (CollectionUtils.isEmpty(service.getComponentInstances())) { + if (CollectionUtils.isEmpty(component.getComponentInstances())) { LOGGER.debug("Component Instance list is empty"); return getErrorResponse(ActionStatus.NODE_FILTER_NOT_FOUND); } - boolean found = - service.getComponentInstances().stream().anyMatch(ci -> ci.getUniqueId().equals(componentInstanceId)); - if (!found) { + if (component.getComponentInstances().stream() + .noneMatch(ci -> ci.getUniqueId().equals(componentInstanceId))) { LOGGER.debug("Component Instance list is empty"); return getErrorResponse(ActionStatus.NODE_FILTER_NOT_FOUND); } @@ -93,20 +91,16 @@ public class NodeFilterValidator { return Either.right(errorResponse); } - public Either<Boolean, ResponseFormat> validateNodeFilter(CINodeFilterDataDefinition nodeFilter, String serviceId, - String complonentInstanceId) { - return Either.left(Boolean.TRUE); - } - - - public Either<Boolean, ResponseFormat> validateNodeFilter(Service parentComponent, String componentInstanceId, - List<String> uiConstraints, NodeFilterConstraintAction action) { + public Either<Boolean, ResponseFormat> validateNodeFilter(final Component parentComponent, + final String componentInstanceId, + final List<String> uiConstraints, + final NodeFilterConstraintAction action) { try { - for (String uiConstraint : uiConstraints) { + for (final String uiConstraint : uiConstraints) { if (NodeFilterConstraintAction.ADD != action && NodeFilterConstraintAction.UPDATE != action) { break; } - UIConstraint constraint = new ConstraintConvertor().convert(uiConstraint); + final UIConstraint constraint = new ConstraintConvertor().convert(uiConstraint); if (ConstraintConvertor.PROPERTY_CONSTRAINT.equals(constraint.getSourceType())) { final Either<Boolean, ResponseFormat> booleanResponseFormatEither = validatePropertyConstraint(parentComponent, componentInstanceId, constraint); @@ -121,7 +115,7 @@ public class NodeFilterValidator { } } } - } catch (Exception e) { + } catch (final Exception e) { LOGGER.debug("Provided constraint" + uiConstraints, e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.CONSTRAINT_FORMAT_INCORRECT)); } @@ -129,10 +123,11 @@ public class NodeFilterValidator { return Either.left(true); } - private Either<Boolean, ResponseFormat> validatePropertyConstraint(Service parentComponent, - String componentInstanceId, UIConstraint uiConstraint) { + private Either<Boolean, ResponseFormat> validatePropertyConstraint( + final Component parentComponent, + final String componentInstanceId, final UIConstraint uiConstraint) { String source = SOURCE; - Optional<ComponentInstance> brotherComponentInstance; + final Optional<ComponentInstance> brotherComponentInstance; List<? extends PropertyDefinition> sourcePropertyDefinition = parentComponent.getName().equals(uiConstraint.getSourceName()) ? parentComponent.getProperties() : @@ -213,12 +208,13 @@ public class NodeFilterValidator { } } - private Either<Boolean, ResponseFormat> validateStaticValueAndOperator(Service parentComponent, - String componentInstanceId, UIConstraint uiConstraint) { + private Either<Boolean, ResponseFormat> validateStaticValueAndOperator( + final Component parentComponent, + final String componentInstanceId, final UIConstraint uiConstraint) { if (!(Objects.nonNull(uiConstraint) && uiConstraint.getValue() instanceof String)) { return Either.left(false); } - Optional<ComponentInstanceProperty> componentInstanceProperty = + final Optional<ComponentInstanceProperty> componentInstanceProperty = parentComponent.getComponentInstancesProperties().get(componentInstanceId).stream() .filter(property -> uiConstraint.getServicePropertyName().equals(property.getName())) .findFirst(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java index 62a30638e6..3479c5f700 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/impl/ComponentsUtils.java @@ -30,7 +30,14 @@ import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import fj.F; import fj.data.Either; -import java.util.function.Function; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletRequest; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.openecomp.sdc.be.auditing.api.AuditEventFactory; @@ -70,13 +77,16 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.graph.datatype.AdditionalInformationEnum; +import org.openecomp.sdc.be.datamodel.utils.ConstraintConvertor; import org.openecomp.sdc.be.datatypes.elements.AdditionalInfoParameterInfo; +import org.openecomp.sdc.be.datatypes.elements.RequirementNodeFilterPropertyDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.CapabilityTypeDefinition; import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; import org.openecomp.sdc.be.model.ConsumerDefinition; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupTypeDefinition; @@ -99,6 +109,7 @@ import org.openecomp.sdc.be.resources.data.auditing.model.OperationalEnvAuditDat import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo; import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo; import org.openecomp.sdc.be.tosca.ToscaError; +import org.openecomp.sdc.be.ui.model.UIConstraint; import org.openecomp.sdc.be.ui.model.UiLeftPaletteComponent; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.enums.LogLevel; @@ -111,12 +122,6 @@ import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.MarkerFactory; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.http.HttpServletRequest; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - @org.springframework.stereotype.Component("componentUtils") public class ComponentsUtils { @@ -1669,6 +1674,53 @@ public class ComponentsUtils { return uiLeftPaletteComponents; } + private static Set<String> getNodesFiltersToBeDeleted(final Component component, + final String componentInstanceName) { + return component.getComponentInstances().stream() + .filter(ci -> isNodeFilterUsingChangedCi(ci, componentInstanceName)) + .map(ComponentInstance::getName).collect(Collectors.toSet()); + } + + public static Set<String> getNodesFiltersToBeDeleted(final Component component, + final ComponentInstance componentInstance) { + return getNodesFiltersToBeDeleted(component, componentInstance.getName()); + } + + private static boolean isNodeFilterUsingChangedCi(final ComponentInstance componentInstance, + final String componentInstanceName) { + if (CollectionUtils.isEmpty(componentInstance.getDirectives())) { + return false; + } + if (componentInstance.getNodeFilter() == null || componentInstance.getNodeFilter().getProperties() == null + || componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition() == null) { + return false; + } + return componentInstance.getNodeFilter().getProperties().getListToscaDataDefinition().stream() + .anyMatch(property -> isPropertyConstraintChangedByCi(property, componentInstanceName)); + } + + private static boolean isPropertyConstraintChangedByCi( + final RequirementNodeFilterPropertyDataDefinition requirementNodeFilterPropertyDataDefinition, + final String componentInstanceName) { + final List<String> constraints = requirementNodeFilterPropertyDataDefinition.getConstraints(); + if (constraints == null) { + return false; + } + return constraints.stream().anyMatch(constraint -> isConstraintChangedByCi(constraint, componentInstanceName)); + } + + private static boolean isConstraintChangedByCi(final String constraint, + final String componentInstanceName) { + final UIConstraint uiConstraint = new ConstraintConvertor().convert(constraint); + if (uiConstraint == null || uiConstraint.getSourceType() == null) { + return false; + } + if (!uiConstraint.getSourceType().equals(ConstraintConvertor.PROPERTY_CONSTRAINT)) { + return false; + } + return uiConstraint.getSourceName().equals(componentInstanceName); + } + public F<StorageOperationStatus, ResponseFormat> toResponseFormat() { return sos -> getResponseFormat(convertFromStorageResponse(sos)); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java index d9a890d399..64f6550bec 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentInstanceServlet.java @@ -38,7 +38,6 @@ import io.swagger.v3.oas.annotations.servers.Server; import io.swagger.v3.oas.annotations.servers.Servers; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.apache.commons.collections.CollectionUtils; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; @@ -46,6 +45,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; @@ -66,11 +66,12 @@ import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentNodeFilterBusinessLogic; import org.openecomp.sdc.be.components.impl.GroupBusinessLogic; import org.openecomp.sdc.be.components.impl.ResourceImportManager; -import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; import org.openecomp.sdc.be.components.impl.aaf.AafPermission; import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; +import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException; import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; import org.openecomp.sdc.be.config.BeEcompErrorManager; @@ -132,19 +133,19 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { private final GroupBusinessLogic groupBL; private final ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - private final ServiceBusinessLogic serviceBusinessLogic; + private final ComponentNodeFilterBusinessLogic nodeFilterBusinessLogic; @Inject public ComponentInstanceServlet(UserBusinessLogic userBusinessLogic, - GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - ServiceBusinessLogic serviceBusinessLogic) { + GroupBusinessLogic groupBL, ComponentInstanceBusinessLogic componentInstanceBL, + ComponentsUtils componentsUtils, ServletUtils servletUtils, + ResourceImportManager resourceImportManager, + ComponentNodeFilterBusinessLogic nodeFilterBusinessLogic) { super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); this.groupBL = groupBL; this.componentInstanceBusinessLogic = componentInstanceBL; - this.serviceBusinessLogic = serviceBusinessLogic; + this.nodeFilterBusinessLogic = nodeFilterBusinessLogic; } @POST @@ -207,64 +208,67 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { schema = @Schema(allowableValues = {ComponentTypeEnum.RESOURCE_PARAM_NAME, ComponentTypeEnum.SERVICE_PARAM_NAME, ComponentTypeEnum.PRODUCT_PARAM_NAME})) @PathParam("containerComponentType") final String containerComponentType, - @Context final HttpServletRequest request) throws IOException { + @Context final HttpServletRequest request) throws IOException, BusinessLogicException { - String url = request.getMethod() + " " + request.getRequestURI(); + final String url = request.getMethod() + " " + request.getRequestURI(); log.debug(START_HANDLE_REQUEST_OF, url); loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE,StatusCode.STARTED,"update Component Instance Metadata"); + final String userId = request.getHeader(Constants.USER_ID_HEADER); + componentInstanceBusinessLogic.validateUser(userId); try { - log.debug(START_HANDLE_REQUEST_OF, url); - - InputStream inputStream = request.getInputStream(); - - byte[] bytes = IOUtils.toByteArray(inputStream); + final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); if (bytes == null || bytes.length == 0) { log.info(EMPTY_BODY_WAS_SENT); return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.INVALID_CONTENT)); } - String userId = request.getHeader(Constants.USER_ID_HEADER); - - String data = new String(bytes); - ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); + final String data = new String(bytes); + final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType); if (componentInstanceBusinessLogic == null) { log.debug(UNSUPPORTED_COMPONENT_TYPE, containerComponentType); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, containerComponentType)); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.UNSUPPORTED_ERROR, + containerComponentType)); } - Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data); - + final Either<ComponentInstance, ResponseFormat> convertResponse = convertToResourceInstance(data); if (convertResponse.isRight()) { BeEcompErrorManager.getInstance().logBeSystemError(RESOURCE_INSTANCE_UPDATE_RESOURCE_INSTANCE); log.debug(FAILED_TO_CONVERT_RECEIVED_DATA_TO_BE_FORMAT); return buildErrorResponse(convertResponse.right().value()); } - ComponentInstance resourceInstance = convertResponse.left().value(); - Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic.updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, resourceInstance); - loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE,actionResponse.left().value().getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"update Component Instance Metadata by {}",userId); + + final ComponentInstance componentInstance = convertResponse.left().value(); + final Either<ComponentInstance, ResponseFormat> actionResponse = componentInstanceBusinessLogic + .updateComponentInstanceMetadata(containerComponentType, componentId, componentInstanceId, userId, componentInstance); + loggerSupportability.log(LoggerSupportabilityActions.UPDATE_COMPONENT_INSTANCE,actionResponse.left().value() + .getComponentMetadataForSupportLog(),StatusCode.COMPLETE,"update Component Instance Metadata by {}", userId); if (actionResponse.isRight()) { return buildErrorResponse(actionResponse.right().value()); } - ComponentInstance resultValue = actionResponse.left().value(); - if (componentTypeEnum.equals(ComponentTypeEnum.SERVICE)){ - if(CollectionUtils.isNotEmpty(resourceInstance.getDirectives())) { - Either<CINodeFilterDataDefinition, ResponseFormat> either = - serviceBusinessLogic.createIfNotAlreadyExistServiceFilter(componentId, componentInstanceId, userId, - true); - if (either.isRight()){ - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance Failed to create service filter."); - log.debug("Failed to create service filter."); + + final ComponentInstance resultValue = actionResponse.left().value(); + if (ComponentTypeEnum.SERVICE.equals(componentTypeEnum) || + ComponentTypeEnum.RESOURCE.equals(componentTypeEnum) && + componentInstanceBusinessLogic.isVFC(componentInstance.getOriginType())) { + + if(CollectionUtils.isNotEmpty(componentInstance.getDirectives())) { + final Optional<CINodeFilterDataDefinition> nodeFilterDataDefinition = + nodeFilterBusinessLogic.createNodeFilterIfNotExist(componentId, componentInstanceId, + true, componentTypeEnum); + if (!nodeFilterDataDefinition.isPresent()){ + BeEcompErrorManager.getInstance().logBeSystemError("Failed to create node filter."); + log.error("Failed to create node filter."); return buildErrorResponse(convertResponse.right().value()); } - resultValue.setNodeFilter(either.left().value()); - + resultValue.setNodeFilter(nodeFilterDataDefinition.get()); } else { - Either<String, ResponseFormat> either = serviceBusinessLogic.deleteIfNotAlreadyDeletedServiceFilter(componentId, componentInstanceId, userId,true); - if (either.isRight()){ - BeEcompErrorManager.getInstance().logBeSystemError("Resource Instance - updateResourceInstance Failed to delete service filter."); - log.debug("Failed to delete service filter."); + final Optional<String> result = nodeFilterBusinessLogic + .deleteNodeFilterIfExists(componentId, componentInstanceId, true, componentTypeEnum); + if (!result.isPresent()){ + BeEcompErrorManager.getInstance().logBeSystemError("Failed to delete node filter."); + log.error("Failed to delete node filter."); return buildErrorResponse(convertResponse.right().value()); } resultValue.setNodeFilter(null); @@ -273,7 +277,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), actionResponse.left().value()); - } catch (Exception e) { + } catch (final Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError(UPDATE_RESOURCE_INSTANCE); log.debug(UPDATE_RESOURCE_INSTANCE_WITH_EXCEPTION, e); throw e; @@ -377,7 +381,7 @@ public class ComponentInstanceServlet extends AbstractValidationsServlet { } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Resource Instance"); log.debug("delete resource instance with exception", e); - throw e; + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServlet.java new file mode 100644 index 0000000000..4a43ab23a6 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ComponentNodeFilterServlet.java @@ -0,0 +1,299 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.servlets; + +import fj.data.Either; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +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.codehaus.jackson.map.ObjectMapper; +import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; +import org.openecomp.sdc.be.components.impl.ComponentNodeFilterBusinessLogic; +import org.openecomp.sdc.be.components.impl.ResourceImportManager; +import org.openecomp.sdc.be.components.impl.aaf.AafPermission; +import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; +import org.openecomp.sdc.be.components.impl.utils.NodeFilterConstraintAction; +import org.openecomp.sdc.be.config.BeEcompErrorManager; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datamodel.utils.ConstraintConvertor; +import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.impl.ComponentsUtils; +import org.openecomp.sdc.be.impl.ServletUtils; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; +import org.openecomp.sdc.be.tosca.utils.NodeFilterConverter; +import org.openecomp.sdc.be.ui.model.UIConstraint; +import org.openecomp.sdc.be.ui.model.UINodeFilter; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Path("/v1/catalog/{componentType}/{componentId}/resourceInstances/{componentInstanceId}/nodeFilter") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +@Singleton +public class ComponentNodeFilterServlet extends AbstractValidationsServlet { + + private static final Logger LOGGER = LoggerFactory.getLogger(ComponentNodeFilterServlet.class); + private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; + private static final String MODIFIER_ID_IS = "modifier id is {}"; + + private static final String FAILED_TO_PARSE_COMPONENT = "failed to parse component"; + + private static final String FAILED_TO_CREATE_NODE_FILTER = "failed to create node filter"; + private static final String NODE_FILTER_CREATION = "Node Filter Creation"; + private static final String CREATE_NODE_FILTER_WITH_AN_ERROR = "create node filter with an error"; + + private static final String FAILED_TO_UPDATE_NODE_FILTER = "failed to update node filter"; + private static final String NODE_FILTER_UPDATE = "Node Filter Update"; + private static final String UPDATE_NODE_FILTER_WITH_AN_ERROR = "update node filter with an error"; + + private static final String FAILED_TO_DELETE_NODE_FILTER = "failed to delete node filter"; + private static final String NODE_FILTER_DELETE = "Node Filter Delete"; + private static final String DELETE_NODE_FILTER_WITH_AN_ERROR = "delete node filter with an error"; + + private final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic; + + @Inject + public ComponentNodeFilterServlet(final UserBusinessLogic userBusinessLogic, + final ComponentInstanceBusinessLogic componentInstanceBL, + final ComponentsUtils componentsUtils, + final ServletUtils servletUtils, + final ResourceImportManager resourceImportManager, + final ComponentNodeFilterBusinessLogic componentNodeFilterBusinessLogic) { + super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); + this.componentNodeFilterBusinessLogic = componentNodeFilterBusinessLogic; + } + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/") + @Operation(description = "Add Component Filter Constraint", method = "POST", + summary = "Add Component Filter Constraint", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Create Component Filter"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) + public Response addComponentFilterConstraint( + @Parameter(description = "UIConstraint data", required = true) String constraintData, + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, + @Parameter(description = "valid values: resources / services", + schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Context final HttpServletRequest request, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); + LOGGER.debug(MODIFIER_ID_IS, userId); + final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId); + + final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + try { + final Either<UIConstraint, ResponseFormat> convertResponse = parseToConstraint(constraintData, userModifier, + componentTypeEnum); + if (convertResponse.isRight()) { + LOGGER.error(FAILED_TO_PARSE_COMPONENT); + return buildErrorResponse(convertResponse.right().value()); + } + final UIConstraint uiConstraint = convertResponse.left().value(); + if (uiConstraint == null) { + LOGGER.debug(FAILED_TO_PARSE_COMPONENT); + return buildErrorResponse(convertResponse.right().value()); + } + final Optional<CINodeFilterDataDefinition> actionResponse; + final String constraint = new ConstraintConvertor().convert(uiConstraint); + actionResponse = componentNodeFilterBusinessLogic + .addNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.ADD, + uiConstraint.getServicePropertyName(), constraint, true, componentTypeEnum); + + if (!actionResponse.isPresent()) { + LOGGER.error(FAILED_TO_CREATE_NODE_FILTER); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + final UINodeFilter nodeFilter = new NodeFilterConverter().convertToUi(actionResponse.get()); + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeFilter); + + } catch (final Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION); + LOGGER.error(CREATE_NODE_FILTER_WITH_AN_ERROR, e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/") + @Operation(description = "Update Component Filter Constraint", method = "PUT", + summary = "Update Component Filter Constraint", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Create Component Filter"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) + public Response updateComponentFilterConstraint( + @Parameter(description = "UIConstraint data", required = true) String constraintData, + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, + @Parameter(description = "valid values: resources / services", + schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); + LOGGER.debug(MODIFIER_ID_IS, userId); + final User userModifier = componentNodeFilterBusinessLogic.validateUser(userId); + + try { + final ComponentTypeEnum componentTypeEnum = ComponentTypeEnum.findByParamName(componentType); + final Either<List, ResponseFormat> convertResponse = parseToConstraints(constraintData, userModifier, + componentTypeEnum); + if (convertResponse.isRight()) { + LOGGER.error(FAILED_TO_PARSE_COMPONENT); + return buildErrorResponse(convertResponse.right().value()); + } + final List<Map<String, String>> uiConstraintsMaps = (List<Map<String, String>>) convertResponse.left() + .value(); + if (uiConstraintsMaps == null) { + LOGGER.debug("failed to parse data"); + return buildErrorResponse(convertResponse.right().value()); + } + final ObjectMapper objectMapper = new ObjectMapper(); + final List<UIConstraint> uiConstraints = uiConstraintsMaps.stream() + .map(dataMap -> objectMapper.convertValue(dataMap, UIConstraint.class)).collect( + Collectors.toList()); + if (uiConstraints == null) { + LOGGER.debug("failed to parse data"); + return buildErrorResponse(convertResponse.right().value()); + } + final Optional<CINodeFilterDataDefinition> actionResponse; + final List<String> constraints = new ConstraintConvertor().convertToList(uiConstraints); + + actionResponse = componentNodeFilterBusinessLogic + .updateNodeFilter(componentId.toLowerCase(), componentInstanceId, constraints, + true, componentTypeEnum); + + if (!actionResponse.isPresent()) { + LOGGER.error(FAILED_TO_UPDATE_NODE_FILTER); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + new NodeFilterConverter().convertToUi(actionResponse.get())); + + } catch (final Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_UPDATE); + LOGGER.error(UPDATE_NODE_FILTER_WITH_AN_ERROR, e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + @DELETE + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/{constraintIndex}") + @Operation(description = "Delete Component Filter Constraint", method = "Delete", + summary = "Delete Component Filter Constraint", responses = { + @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), + @ApiResponse(responseCode = "201", description = "Delete Component Filter Constraint"), + @ApiResponse(responseCode = "403", description = "Restricted operation"), + @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) + @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) + public Response deleteComponentFilterConstraint( + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Component Instance Id") @PathParam("componentInstanceId") String componentInstanceId, + @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index, + @Parameter(description = "valid values: resources / services", + schema = @Schema(allowableValues = { + ComponentTypeEnum.RESOURCE_PARAM_NAME, + ComponentTypeEnum.SERVICE_PARAM_NAME})) @PathParam("componentType") final String componentType, + @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { + + LOGGER.debug(START_HANDLE_REQUEST_OF, request.getMethod(), request.getRequestURI()); + LOGGER.debug(MODIFIER_ID_IS, userId); + componentNodeFilterBusinessLogic.validateUser(userId); + + try { + final Optional<CINodeFilterDataDefinition> actionResponse; + actionResponse = componentNodeFilterBusinessLogic + .deleteNodeFilter(componentId.toLowerCase(), componentInstanceId, NodeFilterConstraintAction.DELETE, + null, index, true, ComponentTypeEnum.findByParamName(componentType)); + + if (!actionResponse.isPresent()) { + LOGGER.debug(FAILED_TO_DELETE_NODE_FILTER); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + new NodeFilterConverter().convertToUi(actionResponse.get())); + + } catch (final Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_DELETE); + LOGGER.debug(DELETE_NODE_FILTER_WITH_AN_ERROR, e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + } + } + + private Either<UIConstraint, ResponseFormat> parseToConstraint(final String componentJson, + final User user, + final ComponentTypeEnum componentTypeEnum) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(componentJson, user, UIConstraint.class, + AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); + } + + private Either<List, ResponseFormat> parseToConstraints(final String componentJson, + final User user, + final ComponentTypeEnum componentTypeEnum) { + return getComponentsUtils().convertJsonToObjectUsingObjectMapper(componentJson, user, List.class, + AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceFilterServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceFilterServlet.java deleted file mode 100644 index a37ab0120f..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/ServiceFilterServlet.java +++ /dev/null @@ -1,306 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.be.servlets; - -import fj.data.Either; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.media.ArraySchema; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.servers.Server; -import io.swagger.v3.oas.annotations.servers.Servers; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.tags.Tags; -import org.codehaus.jackson.map.ObjectMapper; -import org.openecomp.sdc.be.components.impl.ComponentInstanceBusinessLogic; -import org.openecomp.sdc.be.components.impl.ResourceImportManager; -import org.openecomp.sdc.be.components.impl.ServiceBusinessLogic; -import org.openecomp.sdc.be.components.impl.aaf.AafPermission; -import org.openecomp.sdc.be.components.impl.aaf.PermissionAllowed; -import org.openecomp.sdc.be.components.impl.utils.NodeFilterConstraintAction; -import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datamodel.utils.ConstraintConvertor; -import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.impl.ServletUtils; -import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; -import org.openecomp.sdc.be.tosca.utils.NodeFilterConverter; -import org.openecomp.sdc.be.ui.model.UIConstraint; -import org.openecomp.sdc.be.ui.model.UINodeFilter; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.exception.ResponseFormat; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -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 java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Path("/v1/catalog/services/{serviceId}/resourceInstances/{resourceInstanceId}/nodeFilter") -@Consumes(MediaType.APPLICATION_JSON) -@Produces(MediaType.APPLICATION_JSON) -@Tags({@Tag(name = "SDC Internal APIs")}) -@Servers({@Server(url = "/sdc2/rest")}) -@Singleton -public class ServiceFilterServlet extends AbstractValidationsServlet { - - private static final Logger log = LoggerFactory.getLogger(ServiceFilterServlet.class); - private static final String START_HANDLE_REQUEST_OF = "Start handle request of {}"; - private static final String MODIFIER_ID_IS = "modifier id is {}"; - private static final String FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER = "failed to update or create node filter"; - private static final String FAILED_TO_PARSE_SERVICE = "failed to parse service"; - private static final String NODE_FILTER_CREATION_OR_UPDATE = "Node Filter Creation or update"; - private static final String CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR = - "create or update node filter with an error"; - private final ServiceBusinessLogic serviceBusinessLogic; - - @Inject - public ServiceFilterServlet(UserBusinessLogic userBusinessLogic, - ComponentInstanceBusinessLogic componentInstanceBL, - ComponentsUtils componentsUtils, ServletUtils servletUtils, - ResourceImportManager resourceImportManager, - ServiceBusinessLogic serviceBusinessLogic) { - super(userBusinessLogic, componentInstanceBL, componentsUtils, servletUtils, resourceImportManager); - this.serviceBusinessLogic = serviceBusinessLogic; - } - - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Path("/") - @Operation(description = "Add Service Filter Constraint", method = "POST", - summary = "Add Service Filter Constraint", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Create Service Filter"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) - @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response addServiceFilterConstraint(@Parameter(description = "Service data", required = true) String data, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Parameter(description = "Resource Instance Id") @PathParam("resourceInstanceId") String ciId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug(START_HANDLE_REQUEST_OF, url); - final HttpSession session = request.getSession(); - ServletContext context = session.getServletContext(); - User modifier = new User(); - modifier.setUserId(userId); - log.debug(MODIFIER_ID_IS, userId); - - Response response; - - try { - String serviceIdLower = serviceId.toLowerCase(); - - Either<UIConstraint, ResponseFormat> convertResponse = parseToConstraint(data, modifier); - if (convertResponse.isRight()) { - log.debug(FAILED_TO_PARSE_SERVICE); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - UIConstraint uiConstraint = convertResponse.left().value(); - if (uiConstraint == null) { - log.debug(FAILED_TO_PARSE_SERVICE); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - Either<CINodeFilterDataDefinition, ResponseFormat> actionResponse; - String constraint = new ConstraintConvertor().convert(uiConstraint); - actionResponse = serviceBusinessLogic - .addOrDeleteServiceFilter(serviceIdLower, ciId, NodeFilterConstraintAction.ADD, uiConstraint.getServicePropertyName(), - constraint, -1, modifier, true); - - if (actionResponse.isRight()) { - log.debug(FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - CINodeFilterDataDefinition value = actionResponse.left().value(); - UINodeFilter nodeFilter = new NodeFilterConverter().convertToUi(value); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), nodeFilter); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION_OR_UPDATE); - log.debug(CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR, e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @PUT - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Path("/") - @Operation(description = "Update Service Filter Constraint", method = "PUT", - summary = "Update Service Filter Constraint", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Create Service Filter"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) - @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response updateServiceFilterConstraint(@Parameter(description = "Service data", required = true) String data, - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Parameter(description = "Resource Instance Id") @PathParam("resourceInstanceId") String ciId, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug(START_HANDLE_REQUEST_OF, url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug(MODIFIER_ID_IS, userId); - - Response response; - - try { - String serviceIdLower = serviceId.toLowerCase(); - - Either<List, ResponseFormat> convertResponse = parseToConstraints(data, modifier); - if (convertResponse.isRight()) { - log.debug(FAILED_TO_PARSE_SERVICE); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - List<Map<String,String>> uiConstraintsMaps = (List<Map<String,String>>) convertResponse.left().value(); - if (uiConstraintsMaps == null) { - log.debug("failed to parse data"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - final ObjectMapper objectMapper = new ObjectMapper(); - List<UIConstraint> uiConstraints = uiConstraintsMaps.stream().map(dataMap -> objectMapper.convertValue(dataMap, UIConstraint.class)).collect( - Collectors.toList()); - if (uiConstraints == null) { - log.debug("failed to parse data"); - response = buildErrorResponse(convertResponse.right().value()); - return response; - } - Either<CINodeFilterDataDefinition, ResponseFormat> actionResponse; - List<String> constraints = new ConstraintConvertor().convertToList(uiConstraints); - actionResponse = serviceBusinessLogic.updateServiceFilter(serviceIdLower, ciId, constraints, modifier, true); - - if (actionResponse.isRight()) { - log.debug(FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - CINodeFilterDataDefinition value = actionResponse.left().value(); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - new NodeFilterConverter().convertToUi(value)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION_OR_UPDATE); - log.debug(CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR, e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - @DELETE - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Path("/{constraintIndex}") - @Operation(description = "Delete Service Filter Constraint", method = "Delete", - summary = "Delete Service Filter Constraint", responses = { - @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))), - @ApiResponse(responseCode = "201", description = "Delete Service Filter Constraint"), - @ApiResponse(responseCode = "403", description = "Restricted operation"), - @ApiResponse(responseCode = "400", description = "Invalid content / Missing content")}) - @PermissionAllowed(AafPermission.PermNames.INTERNAL_ALL_VALUE) - public Response deleteServiceFilterConstraint( - @Parameter(description = "Service Id") @PathParam("serviceId") String serviceId, - @Parameter(description = "Resource Instance Id") @PathParam("resourceInstanceId") String ciId, - @Parameter(description = "Constraint Index") @PathParam("constraintIndex") int index, - @Context final HttpServletRequest request, @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - String url = request.getMethod() + " " + request.getRequestURI(); - log.debug(START_HANDLE_REQUEST_OF, url); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug(MODIFIER_ID_IS, userId); - - Response response; - - try { - String serviceIdLower = serviceId.toLowerCase(); - - Either<CINodeFilterDataDefinition, ResponseFormat> actionResponse; - actionResponse = serviceBusinessLogic - .addOrDeleteServiceFilter(serviceIdLower, ciId, NodeFilterConstraintAction.DELETE, - null, null, index, modifier, true); - - if (actionResponse.isRight()) { - - log.debug(FAILED_TO_UPDATE_OR_CREATE_NODE_FILTER); - response = buildErrorResponse(actionResponse.right().value()); - return response; - } - - final CINodeFilterDataDefinition value = actionResponse.left().value(); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), - new NodeFilterConverter().convertToUi(value)); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError(NODE_FILTER_CREATION_OR_UPDATE); - log.debug(CREATE_OR_UPDATE_NODE_FILTER_WITH_AN_ERROR, e); - response = buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); - return response; - - } - } - - private Either<UIConstraint, ResponseFormat> parseToConstraint(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, UIConstraint.class, - AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); - } - - private Either<List, ResponseFormat> parseToConstraints(String serviceJson, User user) { - return getComponentsUtils().convertJsonToObjectUsingObjectMapper(serviceJson, user, List.class, - AuditingActionEnum.CREATE_RESOURCE, ComponentTypeEnum.SERVICE); - } -} |