diff options
57 files changed, 2814 insertions, 3091 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java index 2b3ee0ed2e..8f1f5864d5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ArtifactsBusinessLogic.java @@ -56,7 +56,7 @@ import org.openecomp.sdc.be.model.*; import org.openecomp.sdc.be.model.heat.HeatParameterType; import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils; +import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils; import org.openecomp.sdc.be.model.operations.api.*; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder; @@ -179,9 +179,6 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { @Autowired private ArtifactsResolver artifactsResolver; - @Autowired - private InterfaceOperation interfaceOperation; - public enum ArtifactOperationEnum { CREATE, UPDATE, DELETE, DOWNLOAD, LINK; @@ -3058,7 +3055,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } else { return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user, - decodedPayload, componentType, auditingAction, operationUuid, artifactData, prevArtifactId, + decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId, currArtifactId, artifactDefinition); } @@ -3067,7 +3064,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations( Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, - byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, + byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId, ArtifactDefinition artifactDefinition) { StorageOperationStatus error; @@ -3110,24 +3107,15 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } Component storedComponent = componentStorageOperationStatusEither.left().value(); - String interfaceToscaName = InterfaceUtils.createInterfaceToscaResourceName( - storedComponent.getName()); - //fetch the interface from storage - Optional<InterfaceDefinition> interfaceDefinition = - storedComponent.getInterfaces().values().stream() - .filter(interfaceDef -> interfaceDef.getToscaResourceName() - .equals(interfaceToscaName)).findFirst(); - if (!interfaceDefinition.isPresent()) { + Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils + .getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType); + if(!optionalInterface.isPresent()) { log.debug("Failed to get resource interface for resource Id {}", parentId); - ResponseFormat responseFormat = componentsUtils.getResponseFormat( - ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId); - handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, - currArtifactId, responseFormat, componentType, null); - return Either.right(responseFormat); + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType)); } //fetch the operation from storage - InterfaceDefinition gotInterface = interfaceDefinition.get(); + InterfaceDefinition gotInterface = optionalInterface.get(); Map<String, Operation> operationsMap = gotInterface.getOperationsMap(); Optional<Operation> optionalOperation = operationsMap.values() .stream() @@ -3152,8 +3140,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { implementationArtifact.setEsId(artifactInfo.getEsId()); operation.setImplementation(implementationArtifact); gotInterface.setOperationsMap(operationsMap); - Either<InterfaceDefinition, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither = - interfaceOperation.updateInterface(storedComponent.getUniqueId(), gotInterface); + Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither = + interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface)); if (interfaceDefinitionStorageOperationStatusEither.isRight()){ StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value(); ActionStatus actionStatus = @@ -5027,13 +5015,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param componentType * @param componentUuid * @param artifactUUID - * @param operation TODO + * @param operation * @return */ public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID( String data, HttpServletRequest request, ComponentTypeEnum componentType, - String componentUuid, String artifactUUID, String operationUUID, - ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) { + String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID, + ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); Either<ArtifactDefinition, ResponseFormat> updateArtifactResult; Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; @@ -5067,7 +5055,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { resourceCommonInfo.setResourceName(componentName); } if (errorWrapper.isEmpty()) { - Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId); + Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId, interfaceUUID); if (interfaceName.isRight()) { errorWrapper.setInnerElement(interfaceName.right().value()); } @@ -5094,19 +5082,21 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return updateArtifactResult; } - private Either<String, ResponseFormat> fetchInterfaceName(String componentId) { - Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = - toscaOperationFacade.getToscaElement(componentId); + private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) { + Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId); if (componentStorageOperationStatusEither.isRight()) { StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value(); log.debug("Failed to fetch component information by component id, error {}", errorStatus); - return Either.right(componentsUtils - .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); } Component storedComponent = componentStorageOperationStatusEither.left().value(); - return Either.left(InterfaceUtils.createInterfaceToscaResourceName( - storedComponent.getName())); + Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils + .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID); + if(!optionalInterface.isPresent()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID)); + } + return Either.left(optionalInterface.get().getType()); } 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 02e64334f9..8ee1864862 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 @@ -128,10 +128,7 @@ public abstract class BaseBusinessLogic { protected InterfaceOperation interfaceOperation; @Autowired - protected InterfaceOperationBusinessLogic interfaceOperationBusinessLogic; - - @Autowired - protected InterfaceLifecycleOperation interfaceLifecycleOperation; + protected InterfaceLifecycleOperation interfaceLifecycleTypeOperation; @javax.annotation.Resource private UserValidations userValidations; @@ -167,18 +164,6 @@ public abstract class BaseBusinessLogic { this.propertyOperation = propertyOperation; } - public void setInterfaceOperation(InterfaceOperation interfaceOperation) { - this.interfaceOperation = interfaceOperation; - } - public void setInterfaceOperationBusinessLogic(InterfaceOperationBusinessLogic interfaceOperationBusinessLogic) { - this.interfaceOperationBusinessLogic = interfaceOperationBusinessLogic; - } - - - public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) { - this.interfaceLifecycleOperation = interfaceLifecycleOperation; - } - User validateUserNotEmpty(User user, String ecompErrorContext) { return userValidations.validateUserNotEmpty(user, ecompErrorContext); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java index a0efddbdda..2fb7b0f09e 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogic.java @@ -18,15 +18,28 @@ package org.openecomp.sdc.be.components.impl; import fj.data.Either; +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.UUID; +import java.util.stream.Collectors; +import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils; import org.openecomp.sdc.be.components.validation.InterfaceOperationValidation; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; +import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.ArtifactTypeEnum; @@ -36,305 +49,375 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Optional; -import java.util.UUID; -import java.util.stream.Collectors; - @Component("interfaceOperationBusinessLogic") public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceOperationBusinessLogic.class); - private static final String FAILED_TO_LOCK_COMPONENT_RESPONSE_IS = "Failed to lock component {}. Response is {}"; - private static final String EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION = "Exception occurred during {}. Response is {}"; + private static final String EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION = + "Exception occurred during {}. Response is {}"; private static final String DELETE_INTERFACE_OPERATION = "deleteInterfaceOperation"; private static final String GET_INTERFACE_OPERATION = "getInterfaceOperation"; private static final String CREATE_INTERFACE_OPERATION = "createInterfaceOperation"; private static final String UPDATE_INTERFACE_OPERATION = "updateInterfaceOperation"; @Autowired + private ArtifactCassandraDao artifactCassandraDao; + + @Autowired private InterfaceOperationValidation interfaceOperationValidation; - public void setInterfaceOperationValidation(InterfaceOperationValidation interfaceOperationValidation) { - this.interfaceOperationValidation = interfaceOperationValidation; - } + public Either<List<InterfaceDefinition>, ResponseFormat> deleteInterfaceOperation(String componentId, + String interfaceId, List<String> operationsToDelete, User user, boolean lock) { + validateUserExists(user.getUserId(), DELETE_INTERFACE_OPERATION, true); - public Either<Operation, ResponseFormat> deleteInterfaceOperation(String componentId, String interfaceOperationToDelete, User user, boolean lock) { Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); - if (componentEither.isRight()){ + if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - validateUserExists(user.getUserId(), DELETE_INTERFACE_OPERATION, true); - Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, DELETE_INTERFACE_OPERATION); + Either<Boolean, ResponseFormat> lockResult = + lockComponentResult(lock, storedComponent, DELETE_INTERFACE_OPERATION); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); } try { - Optional<InterfaceDefinition> optionalInterface = InterfaceUtils.getInterfaceDefinitionFromToscaName(storedComponent.getInterfaces().values(), storedComponent.getName()); - Either<InterfaceDefinition, ResponseFormat> getInterfaceEither = getInterfaceDefinition(storedComponent, optionalInterface.orElse(null)); - if (getInterfaceEither.isRight()) { - return Either.right(getInterfaceEither.right().value()); + Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils + .getInterfaceDefinitionFromComponentByInterfaceId( + storedComponent, interfaceId); + if (!optionalInterface.isPresent()) { + return Either.right( + componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId)); + } + InterfaceDefinition interfaceDefinition = optionalInterface.get(); + + Map<String, Operation> operationsCollection = new HashMap<>(); + for (String operationId : operationsToDelete) { + Optional<Map.Entry<String, Operation>> optionalOperation = + InterfaceOperationUtils.getOperationFromInterfaceDefinition(interfaceDefinition, operationId); + if (!optionalOperation.isPresent()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, + storedComponent.getUniqueId())); + } + + Operation storedOperation = optionalOperation.get().getValue(); + String artifactUuId = storedOperation.getImplementation().getArtifactUUID(); + CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUuId); + if (cassandraStatus != CassandraOperationStatus.OK) { + ResponseFormat responseFormatByArtifactId = componentsUtils.getResponseFormatByArtifactId( + componentsUtils.convertFromStorageResponse( + componentsUtils.convertToStorageOperationStatus(cassandraStatus)), + storedOperation.getImplementation().getArtifactDisplayName()); + return Either.right(responseFormatByArtifactId); + } + + operationsCollection.put(operationId, interfaceDefinition.getOperationsMap().get(operationId)); + interfaceDefinition.getOperations().remove(operationId); } - InterfaceDefinition interfaceDefinition = getInterfaceEither.left().value(); - Either<Operation, ResponseFormat> getOperationEither = getOperationFromInterfaceDef(storedComponent, interfaceDefinition, interfaceOperationToDelete); - if (getOperationEither.isRight()){ - return Either.right(getOperationEither.right().value()); + Either<List<InterfaceDefinition>, StorageOperationStatus> deleteOperationEither = + interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), + Collections.singletonList(interfaceDefinition)); + if (deleteOperationEither.isRight()) { + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( + deleteOperationEither.right().value(), storedComponent.getComponentType()))); } - Either<Operation, StorageOperationStatus> deleteEither = interfaceOperation.deleteInterfaceOperation(componentId, interfaceDefinition, interfaceOperationToDelete); - if (deleteEither.isRight()){ - LOGGER.error("Failed to delete interface operation from component {}. Response is {}", storedComponent.getName(), deleteEither.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(deleteEither.right().value(), storedComponent.getComponentType()))); + if (interfaceDefinition.getOperations().isEmpty()) { + Either<String, StorageOperationStatus> deleteInterfaceEither = interfaceOperation.deleteInterface( + storedComponent.getUniqueId(), interfaceDefinition.getUniqueId()); + if (deleteInterfaceEither.isRight()) { + titanDao.rollback(); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( + deleteInterfaceEither.right().value(), storedComponent.getComponentType()))); + } } titanDao.commit(); - return Either.left(deleteEither.left().value()); - } - catch (Exception e){ + interfaceDefinition.getOperations().putAll(operationsCollection); + interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToDelete.contains(key))); + return Either.left(Collections.singletonList(interfaceDefinition)); + } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "delete", e); titanDao.rollback(); return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_DELETED)); - } - finally { + } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation.unlockComponent(storedComponent.getUniqueId(), + NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - public Either<Operation, ResponseFormat> getInterfaceOperation(String componentId, String interfaceOperationToGet, User user, boolean lock) { + private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> getComponentDetails(String componentId) { + Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither = + toscaOperationFacade.getToscaElement(componentId); + if (componentStorageOperationStatusEither.isRight()) { + return Either.right(componentsUtils.getResponseFormat( + componentsUtils.convertFromStorageResponse(componentStorageOperationStatusEither.right().value()))); + } + return Either.left(componentStorageOperationStatusEither.left().value()); + } + + private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock, + org.openecomp.sdc.be.model.Component component, String action) { + if (lock) { + Either<Boolean, ResponseFormat> lockResult = lockComponent(component.getUniqueId(), component, action); + if (lockResult.isRight()) { + titanDao.rollback(); + return Either.right(lockResult.right().value()); + } + } + return Either.left(true); + } + + public Either<List<InterfaceDefinition>, ResponseFormat> getInterfaceOperation(String componentId, + String interfaceId, List<String> operationsToGet, User user, boolean lock) { + validateUserExists(user.getUserId(), GET_INTERFACE_OPERATION, true); + Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); - if (componentEither.isRight()){ + if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - validateUserExists(user.getUserId(), GET_INTERFACE_OPERATION, true); - Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, GET_INTERFACE_OPERATION); + Either<Boolean, ResponseFormat> lockResult = + lockComponentResult(lock, storedComponent, GET_INTERFACE_OPERATION); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); } try { - Optional<InterfaceDefinition> optionalInterface = InterfaceUtils.getInterfaceDefinitionFromToscaName(storedComponent.getInterfaces().values(), storedComponent.getName()); - Either<InterfaceDefinition, ResponseFormat> getInterfaceEither = getInterfaceDefinition(storedComponent, optionalInterface.orElse(null)); - if (getInterfaceEither.isRight()) { - return Either.right(getInterfaceEither.right().value()); + Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils + .getInterfaceDefinitionFromComponentByInterfaceId( + storedComponent, interfaceId); + if (!optionalInterface.isPresent()) { + return Either.right( + componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId)); } - InterfaceDefinition interfaceDefinition = getInterfaceEither.left().value(); - - Either<Operation, ResponseFormat> getOperationEither = getOperationFromInterfaceDef(storedComponent, interfaceDefinition, interfaceOperationToGet); - if (getOperationEither.isRight()){ - return Either.right(getOperationEither.right().value()); + InterfaceDefinition interfaceDefinition = optionalInterface.get(); + + for (String operationId : operationsToGet) { + Optional<Map.Entry<String, Operation>> optionalOperation = + InterfaceOperationUtils.getOperationFromInterfaceDefinition(interfaceDefinition, operationId); + if (!optionalOperation.isPresent()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, + storedComponent.getUniqueId())); + } } titanDao.commit(); - return Either.left(getOperationEither.left().value()); - } - catch (Exception e){ + interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToGet.contains(key))); + return Either.left(Collections.singletonList(interfaceDefinition)); + } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e); titanDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId)); - } - finally { + return Either.right( + componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId)); + } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation.unlockComponent(storedComponent.getUniqueId(), + NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - private Either<InterfaceDefinition, ResponseFormat> getInterfaceDefinition(org.openecomp.sdc.be.model.Component component, InterfaceDefinition interfaceDef) { - if (interfaceDef != null){ - return Either.left(interfaceDef); - } else { - InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); - interfaceDefinition.setToscaResourceName(InterfaceUtils.createInterfaceToscaResourceName(component.getName())); - Either<InterfaceDefinition, StorageOperationStatus> interfaceCreateEither = interfaceOperation.addInterface(component.getUniqueId(), interfaceDefinition); - if (interfaceCreateEither.isRight()){ - StorageOperationStatus sValue = interfaceCreateEither.right().value(); - LOGGER.error("Failed to get interface from component {}. Response is {}", component.getName(), sValue); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(sValue, component.getComponentType()), "")); - } - return Either.left(interfaceCreateEither.left().value()); - } + public Either<List<InterfaceDefinition>, ResponseFormat> createInterfaceOperation(String componentId, + List<InterfaceDefinition> interfaceDefinitions, User user, boolean lock) { + return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, false, + CREATE_INTERFACE_OPERATION, lock); } - public Either<Operation, ResponseFormat> createInterfaceOperation(String componentId, Operation operation, User user, boolean lock) { - return createOrUpdateInterfaceOperation(componentId, operation, user, false, CREATE_INTERFACE_OPERATION, lock); - } - - public Either<Operation, ResponseFormat> updateInterfaceOperation(String componentId, Operation operation, User user, boolean lock) { - return createOrUpdateInterfaceOperation(componentId, operation, user, true, UPDATE_INTERFACE_OPERATION, lock); - } + private Either<List<InterfaceDefinition>, ResponseFormat> createOrUpdateInterfaceOperation(String componentId, + List<InterfaceDefinition> interfaceDefinitions, User user, boolean isUpdate, String errorContext, + boolean lock) { + validateUserExists(user.getUserId(), errorContext, true); - private Either<Operation, ResponseFormat> createOrUpdateInterfaceOperation(String componentId, Operation operation, User user, boolean isUpdate, String errorContext, boolean lock) { Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); - if (componentEither.isRight()){ + if (componentEither.isRight()) { return Either.right(componentEither.right().value()); } org.openecomp.sdc.be.model.Component storedComponent = componentEither.left().value(); - validateUserExists(user.getUserId(), errorContext, true); - Either<Boolean, ResponseFormat> interfaceOperationValidationResponseEither = interfaceOperationValidation - .validateInterfaceOperations(Collections.singletonList(operation), storedComponent, isUpdate); - if(interfaceOperationValidationResponseEither.isRight()) { - return Either.right(interfaceOperationValidationResponseEither.right().value()); - } Either<Boolean, ResponseFormat> lockResult = lockComponentResult(lock, storedComponent, errorContext); if (lockResult.isRight()) { return Either.right(lockResult.right().value()); } + Either<Map<String, InterfaceDefinition>, ResponseFormat> interfaceLifecycleTypes = + getAllInterfaceLifecycleTypes(); + if (interfaceLifecycleTypes.isRight()) { + return Either.right(interfaceLifecycleTypes.right().value()); + } + try { - Optional<InterfaceDefinition> optionalInterface = InterfaceUtils.getInterfaceDefinitionFromToscaName(storedComponent.getInterfaces().values(), storedComponent.getName()); - Either<InterfaceDefinition, ResponseFormat> getInterfaceEither = getInterfaceDefinition(storedComponent, optionalInterface.orElse(null)); - if (getInterfaceEither.isRight()) { - return Either.right(getInterfaceEither.right().value()); - } - InterfaceDefinition interfaceDefinition = getInterfaceEither.left().value(); + List<InterfaceDefinition> interfacesCollection = new ArrayList<>(); + Map<String, Operation> operationsCollection = new HashMap<>(); + for (InterfaceDefinition inputInterfaceDefinition : interfaceDefinitions) { + Optional<InterfaceDefinition> optionalInterface = + InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType( + storedComponent, inputInterfaceDefinition.getType()); + Either<Boolean, ResponseFormat> interfaceOperationValidationResponseEither = + interfaceOperationValidation + .validateInterfaceOperations(inputInterfaceDefinition, storedComponent, + optionalInterface.orElse(null), interfaceLifecycleTypes.left().value(), + isUpdate); + if (interfaceOperationValidationResponseEither.isRight()) { + return Either.right(interfaceOperationValidationResponseEither.right().value()); + } - Either<Operation, StorageOperationStatus> result; - if(!isUpdate){ - initNewOperation(operation); - result = interfaceOperation.addInterfaceOperation(componentId, interfaceDefinition, operation); - } - else { - Either<Operation, ResponseFormat> getOperationEither = getOperationFromInterfaceDef(storedComponent, interfaceDefinition, operation.getUniqueId()); - if (getOperationEither.isRight()){ - return Either.right(getOperationEither.right().value()); + Map<String, Operation> operationsToAddOrUpdate = inputInterfaceDefinition.getOperationsMap(); + operationsCollection.putAll(operationsToAddOrUpdate); + inputInterfaceDefinition.getOperations().clear(); + + Either<InterfaceDefinition, ResponseFormat> getInterfaceEither = + getOrCreateInterfaceDefinition(storedComponent, inputInterfaceDefinition, + optionalInterface.orElse(null)); + if (getInterfaceEither.isRight()) { + return Either.right(getInterfaceEither.right().value()); } - updateExistingOperation(operation, getOperationEither.left().value().getImplementation().getArtifactUUID()); - result = interfaceOperation.updateInterfaceOperation(componentId, interfaceDefinition, operation); + InterfaceDefinition interfaceDef = getInterfaceEither.left().value(); + + updateOperationInputDefs(storedComponent, operationsToAddOrUpdate.values()); + + for (Operation operation : operationsToAddOrUpdate.values()) { + if (!isUpdate) { + addOperationToInterface(interfaceDef, operation); + } else { + Optional<Map.Entry<String, Operation>> optionalOperation = + InterfaceOperationUtils.getOperationFromInterfaceDefinition(interfaceDef, + operation.getUniqueId()); + if (!optionalOperation.isPresent()) { + titanDao.rollback(); + return Either.right(componentsUtils + .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, + storedComponent.getUniqueId())); + } + + Operation storedOperation = optionalOperation.get().getValue(); + String artifactUuId = storedOperation.getImplementation().getArtifactUUID(); + Either<Long, CassandraOperationStatus> artifactCount = + artifactCassandraDao.getCountOfArtifactById(artifactUuId); + if (artifactCount.isLeft()) { + CassandraOperationStatus cassandraStatus = + artifactCassandraDao.deleteArtifact(artifactUuId); + if (cassandraStatus != CassandraOperationStatus.OK) { + titanDao.rollback(); + ResponseFormat responseFormatByArtifactId = + componentsUtils.getResponseFormatByArtifactId( + componentsUtils.convertFromStorageResponse( + componentsUtils.convertToStorageOperationStatus( + cassandraStatus)), + storedOperation.getImplementation().getArtifactDisplayName()); + return Either.right(responseFormatByArtifactId); + } + } + updateOperationOnInterface(interfaceDef, operation, artifactUuId); + } + } + interfacesCollection.add(interfaceDef); } - if (result.isRight()) { + Either<List<InterfaceDefinition>, StorageOperationStatus> addCreateOperationEither = + interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), interfacesCollection); + if (addCreateOperationEither.isRight()) { titanDao.rollback(); - LOGGER.debug("Failed to addOrUpdate interface operation on component {}. Response is {}", storedComponent.getName(), result.right().value()); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result.right().value(), storedComponent.getComponentType()))); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( + addCreateOperationEither.right().value(), storedComponent.getComponentType()))); } titanDao.commit(); - return Either.left(result.left().value()); - } - catch (Exception e) { + interfacesCollection.forEach(interfaceDefinition -> interfaceDefinition.getOperations().entrySet().removeIf( + entry -> !operationsCollection.values().stream().map(OperationDataDefinition::getName) + .collect(Collectors.toList()).contains(entry.getValue().getName()))); + return Either.left(interfacesCollection); + } catch (Exception e) { titanDao.rollback(); LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "addOrUpdate", e); return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - finally { + } finally { if (lockResult.isLeft() && lockResult.left().value()) { - graphLockOperation.unlockComponent(storedComponent.getUniqueId(), NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); + graphLockOperation.unlockComponent(storedComponent.getUniqueId(), + NodeTypeEnum.getByNameIgnoreCase(storedComponent.getComponentType().getValue())); } } } - private Either<org.openecomp.sdc.be.model.Component, ResponseFormat> getComponentDetails(String componentId){ - Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId); - if (componentStorageOperationStatusEither.isRight()) { - StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value(); - LOGGER.error("Failed to fetch component information by component id {}, Response is {}", componentId, errorStatus); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus))); - } - return Either.left(componentStorageOperationStatusEither.left().value()); - } + public Either<Map<String, InterfaceDefinition>, ResponseFormat> getAllInterfaceLifecycleTypes() { - private Either<Operation, ResponseFormat> getOperationFromInterfaceDef( - org.openecomp.sdc.be.model.Component component, InterfaceDefinition interfaceDefinition, String operationToFetch) { - Optional<Map.Entry<String, Operation>> operationMap = interfaceDefinition.getOperationsMap().entrySet().stream() - .filter(entry -> entry.getValue().getUniqueId().equals(operationToFetch)).findAny(); - if (!operationMap.isPresent()) { - LOGGER.error("Failed to get interface operation from component {}. Response is {}", component.getUniqueId(), ActionStatus.INTERFACE_OPERATION_NOT_FOUND); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, component.getUniqueId())); + Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfaceLifecycleTypes = + interfaceLifecycleTypeOperation.getAllInterfaceLifecycleTypes(); + if (interfaceLifecycleTypes.isRight()) { + return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_LIFECYCLE_TYPES_NOT_FOUND)); } - return Either.left(operationMap.get().getValue()); - } - - private void initNewOperation(Operation operation){ - ArtifactDefinition artifactDefinition = new ArtifactDefinition(); - String artifactUUID = UUID.randomUUID().toString(); - artifactDefinition.setArtifactUUID(artifactUUID); - artifactDefinition.setUniqueId(artifactUUID); - artifactDefinition.setArtifactType(ArtifactTypeEnum.WORKFLOW.getType()); - artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - operation.setUniqueId(UUID.randomUUID().toString()); - operation.setImplementation(artifactDefinition); - } + interfaceLifecycleTypes.left().value().values().forEach(id -> id.setOperations( + id.getOperations().keySet().stream().collect(Collectors.toMap(key -> key.replaceFirst( + id.getUniqueId() + ".", ""), i -> id.getOperations().get(i))))); - private void updateExistingOperation(Operation operation, String artifactUUID){ - ArtifactDefinition artifactDefinition = new ArtifactDefinition(); - artifactDefinition.setArtifactUUID(artifactUUID); - artifactDefinition.setUniqueId(artifactUUID); - artifactDefinition.setArtifactType(ArtifactTypeEnum.WORKFLOW.getType()); - artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); - operation.setImplementation(artifactDefinition); + return Either.left(interfaceLifecycleTypes.left().value()); } - private Either<Boolean, ResponseFormat> lockComponentResult(boolean lock, org.openecomp.sdc.be.model.Component component, String action){ - if (lock) { - Either<Boolean, ResponseFormat> lockResult = lockComponent(component.getUniqueId(), component, action); - if (lockResult.isRight()) { - LOGGER.debug(FAILED_TO_LOCK_COMPONENT_RESPONSE_IS, component.getName(), lockResult.right().value().getFormattedMessage()); + private Either<InterfaceDefinition, ResponseFormat> getOrCreateInterfaceDefinition( + org.openecomp.sdc.be.model.Component component, InterfaceDefinition interfaceDefinition, + InterfaceDefinition storedInterfaceDef) { + if (storedInterfaceDef != null) { + return Either.left(storedInterfaceDef); + } else { + interfaceDefinition.setUniqueId(UUID.randomUUID().toString()); + interfaceDefinition.setToscaResourceName(interfaceDefinition.getType()); + Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceCreateEither = + interfaceOperation.addInterfaces(component.getUniqueId(), + Collections.singletonList(interfaceDefinition)); + if (interfaceCreateEither.isRight()) { titanDao.rollback(); - return Either.right(lockResult.right().value()); + return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse( + interfaceCreateEither.right().value(), component.getComponentType()))); } + return Either.left(interfaceCreateEither.left().value().get(0)); } - return Either.left(true); } - public Either<Boolean, ResponseFormat> validateComponentNameAndUpdateInterfaces(org.openecomp.sdc.be.model.Component oldComponent, - org.openecomp.sdc.be.model.Component newComponent) { - if(!oldComponent.getName().equals(newComponent.getName()) ) { - Collection<InterfaceDefinition> interfaceDefinitionListFromToscaName = InterfaceUtils - .getInterfaceDefinitionListFromToscaName(oldComponent.getInterfaces().values(), - oldComponent.getName()); - for (InterfaceDefinition interfaceDefinition : interfaceDefinitionListFromToscaName) { - - Either<InterfaceDefinition, ResponseFormat> interfaceDefinitionResponseEither = updateInterfaceDefinition(oldComponent, - newComponent, interfaceDefinition); - if(interfaceDefinitionResponseEither.isRight()) { - return Either.right(interfaceDefinitionResponseEither.right().value()); - } - } - } - return Either.left(Boolean.TRUE); + private void updateOperationInputDefs(org.openecomp.sdc.be.model.Component component, + Collection<Operation> interfaceOperations) { + interfaceOperations.stream().filter(operation -> Objects.nonNull(operation.getInputs())).forEach( + operation -> operation.getInputs().getListToscaDataDefinition().forEach( + inp -> component.getInputs().stream().filter(in -> inp.getInputId().equals(in.getUniqueId())) + .forEach(in -> { + inp.setDefaultValue(in.getDefaultValue()); + inp.setValue(in.getValue()); + inp.setSchema(in.getSchema()); + }))); } - private Either<InterfaceDefinition, ResponseFormat > updateInterfaceDefinition(org.openecomp.sdc.be.model.Component oldComponent, - org.openecomp.sdc.be.model.Component newComponent, - InterfaceDefinition interfaceDefinition) { - InterfaceUtils.createInterfaceToscaResourceName(newComponent.getName()); - interfaceDefinition.setToscaResourceName(InterfaceUtils - .createInterfaceToscaResourceName(newComponent.getName())); - try { - Either<InterfaceDefinition, StorageOperationStatus> interfaceUpdate = interfaceOperation - .updateInterface(oldComponent.getUniqueId(), interfaceDefinition); - if (interfaceUpdate.isRight()) { - LOGGER.error("Failed to Update interface {}. Response is {}. ", newComponent.getName(), interfaceUpdate.right().value()); - titanDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(interfaceUpdate.right().value(), ComponentTypeEnum.RESOURCE))); - } - } catch (Exception e) { - LOGGER.error("Exception occurred during update interface toscaResourceName : {}", e); - titanDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR)); - } - return Either.left( interfaceDefinition); + + private void addOperationToInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation) { + interfaceOperation.setUniqueId(UUID.randomUUID().toString()); + interfaceOperation.setImplementation(createArtifactDefinition(UUID.randomUUID().toString())); + interfaceDefinition.getOperations() + .put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation)); } - public Either<Map<String, InterfaceDefinition>, ResponseFormat> getAllInterfaceLifecycleTypes() { + private void updateOperationOnInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation, + String artifactUuId) { + interfaceOperation.setImplementation(createArtifactDefinition(artifactUuId)); + interfaceDefinition.getOperations() + .put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation)); + } - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfaceLifecycleTypes = interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(); - if(interfaceLifecycleTypes.isRight()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_LIFECYCLE_TYPES_NOT_FOUND)); - } - interfaceLifecycleTypes.left().value().values().stream().forEach( - id -> id.setOperations(id.getOperations().keySet().stream().collect(Collectors.toMap(key -> key.replaceFirst(id.getUniqueId()+".",""), i -> id.getOperations().get(i))))); + private ArtifactDefinition createArtifactDefinition(String artifactUuId) { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setArtifactUUID(artifactUuId); + artifactDefinition.setUniqueId(artifactUuId); + artifactDefinition.setArtifactType(ArtifactTypeEnum.WORKFLOW.getType()); + artifactDefinition.setArtifactGroupType(ArtifactGroupTypeEnum.DEPLOYMENT); + return artifactDefinition; + } - return Either.left(interfaceLifecycleTypes.left().value()); + public Either<List<InterfaceDefinition>, ResponseFormat> updateInterfaceOperation(String componentId, + List<InterfaceDefinition> interfaceDefinitions, User user, boolean lock) { + return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, true, + UPDATE_INTERFACE_OPERATION, lock); } + } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java index 7917a0aa5d..4e842928ef 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogic.java @@ -3984,14 +3984,6 @@ public class ResourceBusinessLogic extends ComponentBusinessLogic { newResource.setDerivedFrom(null); } - Either<Boolean, ResponseFormat> validateAndUpdateInterfacesEither = - interfaceOperationBusinessLogic.validateComponentNameAndUpdateInterfaces(currentResource, newResource); - if (validateAndUpdateInterfacesEither.isRight()) { - log.error("failed to validate and update Interfaces"); - rollbackNeeded = true; - throw new ComponentException(validateAndUpdateInterfacesEither.right().value()); - } - Either<Resource, ResponseFormat> dataModelResponse = updateResourceMetadata(resourceIdToUpdate, newResource, user, currentResource, false, true); if (dataModelResponse.isRight()) { 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 e85afdc48f..8d4f896d47 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 @@ -518,11 +518,7 @@ public class ServiceBusinessLogic extends ComponentBusinessLogic { log.info("Restricted operation for user: {}, on service: {}", user.getUserId(), currentService.getCreatorUserId()); return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION)); } - Either<Boolean, ResponseFormat> validateAndUpdateInterfacesEither = interfaceOperationBusinessLogic.validateComponentNameAndUpdateInterfaces(currentService, serviceUpdate); - if (validateAndUpdateInterfacesEither.isRight()) { - log.info("failed to validate and update Interfaces on service {}", currentService.getCreatorUserId()); - return Either.right(validateAndUpdateInterfacesEither.right().value()); - } + Either<Service, ResponseFormat> validationRsponse = validateAndUpdateServiceMetadata(user, currentService, serviceUpdate); if (validationRsponse.isRight()) { log.info("service update metadata: validations field."); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtils.java new file mode 100644 index 0000000000..0233711a89 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtils.java @@ -0,0 +1,64 @@ +/* + * Copyright © 2016-2018 European Support Limited + * + * 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. + */ + +package org.openecomp.sdc.be.components.utils; + +import java.util.Map; +import java.util.Optional; +import org.apache.commons.collections.MapUtils; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.Operation; + +public class InterfaceOperationUtils { + + private InterfaceOperationUtils() { + } + + public static Optional<InterfaceDefinition> getInterfaceDefinitionFromComponentByInterfaceType(Component component, + String interfaceType) { + if (MapUtils.isEmpty(component.getInterfaces())) { + return Optional.empty(); + } + return component.getInterfaces().values().stream() + .filter(interfaceDefinition -> interfaceDefinition.getType() != null && interfaceDefinition + .getType() + .equals(interfaceType)) + .findAny(); + } + + public static Optional<InterfaceDefinition> getInterfaceDefinitionFromComponentByInterfaceId(Component component, + String interfaceId) { + if (MapUtils.isEmpty(component.getInterfaces())) { + return Optional.empty(); + } + return component.getInterfaces().values().stream() + .filter(interfaceDefinition -> interfaceDefinition.getUniqueId() != null && interfaceDefinition + .getUniqueId() + .equals(interfaceId)) + .findAny(); + } + + public static Optional<Map.Entry<String, Operation>> getOperationFromInterfaceDefinition( + InterfaceDefinition interfaceDefinition, String operationId) { + if (MapUtils.isEmpty(interfaceDefinition.getOperationsMap())) { + return Optional.empty(); + } + return interfaceDefinition.getOperationsMap().entrySet().stream() + .filter(entry -> entry.getValue().getUniqueId().equals(operationId)).findAny(); + } + +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidation.java b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidation.java index 7b650e4fad..c80f57486d 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidation.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidation.java @@ -16,6 +16,7 @@ package org.openecomp.sdc.be.components.validation; +import fj.data.Either; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -25,16 +26,11 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import fj.data.Either; +import java.util.stream.Stream; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; -import org.elasticsearch.common.Strings; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition; import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; @@ -47,272 +43,339 @@ import org.springframework.stereotype.Component; @Component("interfaceOperationValidation") public class InterfaceOperationValidation { - private static final String TYPE_VALIDATION_REGEX = "^[a-zA-Z]{1,200}$"; - private static final int DESCRIPTION_MAX_LENGTH = 200; + private static final String TYPE_VALIDATION_REGEX = "^[a-zA-Z0-9_]{1,200}$"; private static final Logger LOGGER = LoggerFactory.getLogger(InterfaceOperationValidation.class); - public Either<Boolean, ResponseFormat> validateInterfaceOperations( - Collection<Operation> interfaceOperations, org.openecomp.sdc.be.model.Component component, boolean isUpdate) { + public Either<Boolean, ResponseFormat> validateInterfaceOperations(InterfaceDefinition inputInterfaceDefinition, + org.openecomp.sdc.be.model.Component component, InterfaceDefinition storedInterfaceDefinition, + Map<String, InterfaceDefinition> globalInterfaceTypes, boolean isUpdate) { + + Either<Boolean, ResponseFormat> validateAllowedOperationCountOnLocalInterfaceType = + validateAllowedOperationCountOnLocalInterfaceType(inputInterfaceDefinition, storedInterfaceDefinition, + globalInterfaceTypes, isUpdate); + if (validateAllowedOperationCountOnLocalInterfaceType.isRight()) { + return validateAllowedOperationCountOnLocalInterfaceType; + } + + Either<Boolean, ResponseFormat> validateAllowedOperationsOnGlobalInterfaceType = + validateAllowedOperationsOnGlobalInterfaceType(inputInterfaceDefinition, globalInterfaceTypes); + if (validateAllowedOperationsOnGlobalInterfaceType.isRight()) { + return validateAllowedOperationsOnGlobalInterfaceType; + } - for(Operation interfaceOperation : interfaceOperations) { - Either<Boolean, ResponseFormat> interfaceOperationValidatorResponse = validateInterfaceOperation( - interfaceOperation, component, isUpdate); + Either<Boolean, ResponseFormat> validateOperationNameUniqueness = + validateOperationNameUniquenessInCollection(inputInterfaceDefinition.getOperationsMap().values()); + if (validateOperationNameUniqueness.isRight()) { + return validateOperationNameUniqueness; + } + + for (Operation interfaceOperation : inputInterfaceDefinition.getOperationsMap().values()) { + Either<Boolean, ResponseFormat> interfaceOperationValidatorResponse = + validateInterfaceOperation(interfaceOperation, storedInterfaceDefinition, component, isUpdate); if (interfaceOperationValidatorResponse.isRight()) { return interfaceOperationValidatorResponse; } } + return Either.left(Boolean.TRUE); } - private Either<Boolean, ResponseFormat> validateInterfaceOperation(Operation interfaceOperation, - org.openecomp.sdc.be.model.Component component, boolean isUpdate) { - ResponseFormatManager responseFormatManager = getResponseFormatManager(); + private Either<Boolean, ResponseFormat> validateAllowedOperationCountOnLocalInterfaceType( + InterfaceDefinition inputInterfaceDefinition, InterfaceDefinition storedInterfaceDefinition, + Map<String, InterfaceDefinition> globalInterfaceTypes, boolean isUpdate) { + + boolean isInterfaceTypeExistInGlobalType = + globalInterfaceTypes.values().stream().map(InterfaceDefinition::getType) + .anyMatch(type -> type.equalsIgnoreCase(inputInterfaceDefinition.getType())); + if (!isInterfaceTypeExistInGlobalType + && (inputInterfaceDefinition.getOperations().size() > 1 + || (!isUpdate && storedInterfaceDefinition != null + && storedInterfaceDefinition.getType() + .equalsIgnoreCase(inputInterfaceDefinition.getType())))) { + return Either.right(getResponseFormatManager() + .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INVALID_FOR_LOCAL_TYPE, + inputInterfaceDefinition.getType())); + } - Either<Boolean, ResponseFormat> interfaceOperationTypeResponse = isInterfaceOperationTypeValid(interfaceOperation, - responseFormatManager, component, isUpdate); - if (interfaceOperationTypeResponse.isRight()) { - return Either.right(interfaceOperationTypeResponse.right().value()); + return Either.left(Boolean.TRUE); + } + + private Either<Boolean, ResponseFormat> validateAllowedOperationsOnGlobalInterfaceType( + InterfaceDefinition interfaceDefinition, Map<String, InterfaceDefinition> globalInterfaceTypes) { + + if (globalInterfaceTypes != null) { + boolean isOperationValidOnGlobalInterfaceType = + Stream.of(interfaceDefinition) + .filter(interfaceDef -> globalInterfaceTypes.values().stream().anyMatch( + interfaceDef1 -> interfaceDef1.getType().equalsIgnoreCase(interfaceDef.getType()))) + .flatMap(interfaceDef -> interfaceDef.getOperationsMap().values().stream() + .map(Operation::getName)) + .allMatch(operationName -> globalInterfaceTypes.values().stream() + .flatMap(interfaceDef -> interfaceDef.getOperationsMap() + .keySet().stream()) + .anyMatch(opName -> + opName.equalsIgnoreCase( + operationName))); + if (!isOperationValidOnGlobalInterfaceType) { + return Either.right(getResponseFormatManager() + .getResponseFormat(ActionStatus.INTERFACE_OPERATION_INVALID_FOR_GLOBAL_TYPE, + interfaceDefinition.getType())); + } } + return Either.left(Boolean.TRUE); + } - Either<Boolean, ResponseFormat> descriptionResponseEither = isValidDescription(responseFormatManager, - interfaceOperation.getDescription()); - if (descriptionResponseEither.isRight()) { - return Either.right(descriptionResponseEither.right().value()); + private Either<Boolean, ResponseFormat> validateOperationNameUniquenessInCollection( + Collection<Operation> operationList) { + HashSet<String> operationNames = new HashSet<>(); + for (Operation operation : operationList) { + if (!operationNames.add(operation.getName())) { + return Either.right(getResponseFormatManager() + .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE, + operation.getName())); + } } + return Either.left(Boolean.TRUE); + } - Either<Boolean, ResponseFormat> inputPropertyExistInComponent = validateInputPropertyExistInComponent(interfaceOperation, - component.getInputs(), responseFormatManager); - if(inputPropertyExistInComponent.isRight()) { - return Either.right(inputPropertyExistInComponent.right().value()); + private Either<Boolean, ResponseFormat> validateInterfaceOperation(Operation interfaceOperation, + InterfaceDefinition interfaceDefinition, org.openecomp.sdc.be.model.Component component, boolean isUpdate) { + ResponseFormatManager responseFormatManager = getResponseFormatManager(); + Either<Boolean, ResponseFormat> interfaceOperationTypeResponse = + isInterfaceOperationTypeValid(interfaceOperation, responseFormatManager, interfaceDefinition, isUpdate); + if (interfaceOperationTypeResponse.isRight()) { + return Either.right(interfaceOperationTypeResponse.right().value()); } - Either<Boolean, ResponseFormat> inputParametersResponse = validateInputParameters(interfaceOperation, - responseFormatManager); - if(inputParametersResponse.isRight()) { - return Either.right(inputParametersResponse.right().value()); + if (null != interfaceOperation.getInputs()) { + Either<Boolean, ResponseFormat> inputParametersResponse = + validateInputParameters(interfaceOperation, responseFormatManager); + if (inputParametersResponse.isRight()) { + return Either.right(inputParametersResponse.right().value()); + } + + Either<Boolean, ResponseFormat> inputPropertyExistInComponent = + validateInputPropertyExistInComponent(interfaceOperation, component, responseFormatManager); + if (inputPropertyExistInComponent.isRight()) { + return Either.right(inputPropertyExistInComponent.right().value()); + + } } - Either<Boolean, ResponseFormat> outputParametersResponse = validateOutputParameters(interfaceOperation, - responseFormatManager); - if(outputParametersResponse.isRight()) { - return Either.right(outputParametersResponse.right().value()); + if (null != interfaceOperation.getOutputs()) { + Either<Boolean, ResponseFormat> outputParametersResponse = + validateOutputParameters(interfaceOperation, responseFormatManager); + if (outputParametersResponse.isRight()) { + return Either.right(outputParametersResponse.right().value()); + } } return Either.left(Boolean.TRUE); } + protected ResponseFormatManager getResponseFormatManager() { + return ResponseFormatManager.getInstance(); + } + private Either<Boolean, ResponseFormat> isInterfaceOperationTypeValid(Operation interfaceOperation, - ResponseFormatManager responseFormatManager, - org.openecomp.sdc.be.model.Component component, boolean isUpdate) { + ResponseFormatManager responseFormatManager, InterfaceDefinition interfaceDefinition, boolean isUpdate) { Either<Boolean, ResponseFormat> operationTypeEmptyEither = - isOperationTypeEmpty(responseFormatManager, interfaceOperation.getName()); + isOperationTypeEmpty(responseFormatManager, interfaceOperation.getName()); if (operationTypeEmptyEither.isRight()) { return Either.right(operationTypeEmptyEither.right().value()); } Either<Boolean, ResponseFormat> operationTypeRegexValidationResponse = - isOperationTypeRegexValid(responseFormatManager, interfaceOperation.getName()); + isOperationTypeRegexValid(responseFormatManager, interfaceOperation.getName()); if (operationTypeRegexValidationResponse.isRight()) { return Either.right(operationTypeRegexValidationResponse.right().value()); } - Either<Boolean, ResponseFormat> operationTypeUniqueResponse = validateOperationTypeUnique(interfaceOperation, - component, isUpdate ); - if(operationTypeUniqueResponse.isRight()) { + Either<Boolean, ResponseFormat> operationTypeUniqueResponse = + validateOperationTypeUnique(interfaceOperation, interfaceDefinition, isUpdate); + if (operationTypeUniqueResponse.isRight()) { return Either.right(operationTypeUniqueResponse.right().value()); } if (!operationTypeUniqueResponse.left().value()) { LOGGER.error("Interface Operation type {} already in use ", interfaceOperation.getName()); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_NAME_ALREADY_IN_USE, interfaceOperation.getName()); + ResponseFormat errorResponse = responseFormatManager.getResponseFormat( + ActionStatus.INTERFACE_OPERATION_NAME_ALREADY_IN_USE, interfaceOperation.getName()); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either<Boolean, ResponseFormat> isOperationTypeRegexValid(ResponseFormatManager responseFormatManager, - String operationType) { - if (!isValidOperationType(operationType)) { - LOGGER.error("Interface Operation type {} is invalid, Operation type should not contain" + - "Special character, space, numbers and should not be greater than 200 characters", operationType); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_NAME_INVALID, operationType); - return Either.right(errorResponse); + private Either<Boolean, ResponseFormat> validateInputParameters(Operation interfaceOperation, + ResponseFormatManager responseFormatManager) { + if (isInputParameterNameEmpty(interfaceOperation)) { + LOGGER.error("Interface operation input parameter name can't be empty"); + ResponseFormat inputResponse = + responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_MANDATORY); + return Either.right(inputResponse); + } + + Either<Boolean, Set<String>> validateInputParametersUniqueResponse = + isInputParametersUnique(interfaceOperation); + if (validateInputParametersUniqueResponse.isRight()) { + LOGGER.error("Interface operation input parameter names {} already in use", + validateInputParametersUniqueResponse.right().value()); + ResponseFormat inputResponse = responseFormatManager.getResponseFormat( + ActionStatus.INTERFACE_OPERATION_INPUT_NAME_ALREADY_IN_USE, + validateInputParametersUniqueResponse.right().value().toString()); + return Either.right(inputResponse); + } + return Either.left(Boolean.TRUE); + } + + private Either<Boolean, ResponseFormat> validateInputPropertyExistInComponent(Operation operation, + org.openecomp.sdc.be.model.Component component, ResponseFormatManager responseFormatManager) { + + List<OperationInputDefinition> inputListToscaDataDefinition = + operation.getInputs().getListToscaDataDefinition(); + for (OperationInputDefinition inputDefinition : inputListToscaDataDefinition) { + if (!validateInputExistsInComponent(inputDefinition, component.getInputs())) { + String missingPropertyName = inputDefinition.getInputId().contains(".") + ? inputDefinition.getInputId().substring( + inputDefinition.getInputId().indexOf('.') + 1) + : inputDefinition.getInputId(); + LOGGER.error("Interface operation input property {} not found in component input properties", + missingPropertyName); + ResponseFormat inputResponse = responseFormatManager.getResponseFormat( + ActionStatus.INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT, missingPropertyName, + component.getComponentType().getValue()); + return Either.right(inputResponse); + } + } + return Either.left(Boolean.TRUE); + } + + private Either<Boolean, ResponseFormat> validateOutputParameters(Operation interfaceOperation, + ResponseFormatManager responseFormatManager) { + if (isOutputParameterNameEmpty(interfaceOperation)) { + LOGGER.error("Interface operation output parameter name can't be empty"); + ResponseFormat inputResponse = + responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_MANDATORY); + return Either.right(inputResponse); + } + + Either<Boolean, Set<String>> validateOutputParametersUniqueResponse = + isOutputParametersUnique(interfaceOperation); + if (validateOutputParametersUniqueResponse.isRight()) { + LOGGER.error("Interface operation output parameter names {} already in use", + validateOutputParametersUniqueResponse.right().value()); + ResponseFormat inputResponse = responseFormatManager.getResponseFormat( + ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_ALREADY_IN_USE, + validateOutputParametersUniqueResponse.right().value().toString()); + return Either.right(inputResponse); } return Either.left(Boolean.TRUE); } private Either<Boolean, ResponseFormat> isOperationTypeEmpty(ResponseFormatManager responseFormatManager, - String operationType) { + String operationType) { if (StringUtils.isEmpty(operationType)) { LOGGER.error("Interface Operation type is mandatory"); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_NAME_MANDATORY); + ResponseFormat errorResponse = + responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_MANDATORY); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private Either<Boolean, ResponseFormat> isValidDescription(ResponseFormatManager responseFormatManager, - String description) { - if (!Strings.isNullOrEmpty(description) && description.length() > DESCRIPTION_MAX_LENGTH) { - LOGGER.error("Interface Operation description {} is invalid, maximum 200 characters allowed", description); - ResponseFormat errorResponse = responseFormatManager.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_DESCRIPTION_MAX_LENGTH, description); + private Either<Boolean, ResponseFormat> isOperationTypeRegexValid(ResponseFormatManager responseFormatManager, + String operationType) { + if (!isValidOperationType(operationType)) { + LOGGER.error("Interface Operation type {} is invalid, Operation type should not contain" + + "Special character, space, numbers and should not be greater than 200 characters", + operationType); + ResponseFormat errorResponse = responseFormatManager + .getResponseFormat(ActionStatus.INTERFACE_OPERATION_NAME_INVALID, + operationType); return Either.right(errorResponse); } return Either.left(Boolean.TRUE); } - private boolean isValidOperationType(String operationType) { - return Pattern.matches(TYPE_VALIDATION_REGEX, operationType); - } - - private Either<Boolean, ResponseFormat> validateOperationTypeUnique( - Operation interfaceOperation, - org.openecomp.sdc.be.model.Component component, - boolean isUpdate) { + private Either<Boolean, ResponseFormat> validateOperationTypeUnique(Operation interfaceOperation, + InterfaceDefinition interfaceDefinition, boolean isUpdate) { boolean isOperationTypeUnique = false; - Map<String, InterfaceDefinition> interfaceDefinitionMap = component.getInterfaces(); - if(interfaceDefinitionMap.isEmpty()){ - return Either.left(true); - } - - Collection<Operation> allOperations = interfaceDefinitionMap.values().stream() - .filter(a -> MapUtils.isNotEmpty(a.getOperationsMap())) - .map(a -> a.getOperationsMap().values()).flatMap(Collection::stream) - .collect(Collectors.toList()); - if(CollectionUtils.isEmpty(allOperations)){ + if (interfaceDefinition == null || CollectionUtils.isEmpty(interfaceDefinition.getOperationsMap().values())) { return Either.left(true); } Map<String, String> operationTypes = new HashMap<>(); - allOperations.forEach(operationType -> operationTypes.put(operationType.getUniqueId(), operationType.getName())); + interfaceDefinition.getOperationsMap().values() + .forEach(operationType -> operationTypes.put(operationType.getUniqueId(), operationType.getName())); - if (!operationTypes.values().contains(interfaceOperation.getName())){ + if (!operationTypes.values().contains(interfaceOperation.getName())) { isOperationTypeUnique = true; } - if (!isOperationTypeUnique && isUpdate){ - Optional<String> id = operationTypes.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(), interfaceOperation.getName())) - .map(Map.Entry::getKey).findAny(); - if(id.isPresent() && id.get().equalsIgnoreCase(interfaceOperation.getUniqueId())){ + if (!isOperationTypeUnique && isUpdate) { + Optional<String> id = operationTypes.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(), + interfaceOperation.getName())).map(Map.Entry::getKey).findAny(); + if (id.isPresent() && id.get().equalsIgnoreCase(interfaceOperation.getUniqueId())) { isOperationTypeUnique = true; } } return Either.left(isOperationTypeUnique); } - private Either<Boolean, ResponseFormat> validateInputParameters(Operation interfaceOperation, - ResponseFormatManager responseFormatManager) { - if (isInputParameterNameEmpty(interfaceOperation)) { - LOGGER.error("Interface operation input parameter name can't be empty"); - ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_NAME_MANDATORY); - return Either.right(inputResponse); - } - Either<Boolean, Set<String>> validateInputParametersUniqueResponse = isInputParametersUnique(interfaceOperation); - if(validateInputParametersUniqueResponse.isRight()) { - LOGGER.error("Interface operation input parameter names {} already in use", - validateInputParametersUniqueResponse.right().value()); - ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_INPUT_NAME_ALREADY_IN_USE, validateInputParametersUniqueResponse.right().value().toString()); - return Either.right(inputResponse); - } - return Either.left(Boolean.TRUE); + private Boolean isInputParameterNameEmpty(Operation operationDataDefinition) { + return operationDataDefinition.getInputs().getListToscaDataDefinition().stream().anyMatch( + inputParam -> inputParam.getName() == null || inputParam.getName().trim().equals(StringUtils.EMPTY)); } - - private Either<Boolean, ResponseFormat> validateOutputParameters(Operation interfaceOperation, - ResponseFormatManager responseFormatManager) { - if (isOutputParameterNameEmpty(interfaceOperation)) { - LOGGER.error("Interface operation output parameter name can't be empty"); - ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_OUTPUT_NAME_MANDATORY); - return Either.right(inputResponse); - } - - Either<Boolean, Set<String>> validateOutputParametersUniqueResponse = isOutputParametersUnique(interfaceOperation); - if(validateOutputParametersUniqueResponse.isRight()) { - LOGGER.error("Interface operation output parameter names {} already in use", - validateOutputParametersUniqueResponse.right().value()); - ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus - .INTERFACE_OPERATION_OUTPUT_NAME_ALREADY_IN_USE, validateOutputParametersUniqueResponse.right().value().toString()); - return Either.right(inputResponse); - } - return Either.left(Boolean.TRUE); - } private Either<Boolean, Set<String>> isInputParametersUnique(Operation operationDataDefinition) { Set<String> inputParamNamesSet = new HashSet<>(); Set<String> duplicateParamNamesToReturn = new HashSet<>(); - operationDataDefinition.getInputs().getListToscaDataDefinition() - .forEach(inputParam -> { - if(!inputParamNamesSet.add(inputParam.getName().trim())) { - duplicateParamNamesToReturn.add(inputParam.getName().trim()); - } - }); - if(!duplicateParamNamesToReturn.isEmpty()) { + operationDataDefinition.getInputs().getListToscaDataDefinition().forEach(inputParam -> { + if (!inputParamNamesSet.add(inputParam.getName().trim())) { + duplicateParamNamesToReturn.add(inputParam.getName().trim()); + } + }); + if (!duplicateParamNamesToReturn.isEmpty()) { return Either.right(duplicateParamNamesToReturn); } return Either.left(Boolean.TRUE); } - private Either<Boolean, Set<String>> isOutputParametersUnique(Operation operationDataDefinition) { - Set<String> outputParamNamesSet = new HashSet<>(); - Set<String> duplicateParamNamesToReturn = new HashSet<>(); - operationDataDefinition.getOutputs().getListToscaDataDefinition() - .forEach(outputParam -> { - if(!outputParamNamesSet.add(outputParam.getName().trim())) { - duplicateParamNamesToReturn.add(outputParam.getName().trim()); - } - }); - if(!duplicateParamNamesToReturn.isEmpty()) { - return Either.right(duplicateParamNamesToReturn); - } - return Either.left(Boolean.TRUE); + private boolean validateInputExistsInComponent(OperationInputDefinition input, List<InputDefinition> inputs) { + return inputs.stream().anyMatch(inp -> inp.getUniqueId().equals(input.getInputId())) + || (input.getInputId().contains(".") + && inputs.stream() + .anyMatch(inp -> inp.getUniqueId() + .equals(input.getInputId() + .substring(0, + input.getInputId() + .lastIndexOf('.'))))); } - private Boolean isInputParameterNameEmpty(Operation operationDataDefinition) { - return operationDataDefinition.getInputs().getListToscaDataDefinition().stream() - .anyMatch(inputParam -> inputParam.getName() == null || inputParam.getName().trim().equals(StringUtils.EMPTY)); - } private Boolean isOutputParameterNameEmpty(Operation operationDataDefinition) { - return operationDataDefinition.getOutputs().getListToscaDataDefinition().stream() - .anyMatch(outputParam -> outputParam.getName() == null || outputParam.getName().trim().equals(StringUtils.EMPTY)); + return operationDataDefinition.getOutputs().getListToscaDataDefinition().stream().anyMatch( + outputParam -> outputParam.getName() == null || outputParam.getName().trim().equals(StringUtils.EMPTY)); } - private Either<Boolean, ResponseFormat> validateInputPropertyExistInComponent(Operation operation, - List<InputDefinition> inputs, - ResponseFormatManager responseFormatManager) { - ListDataDefinition<OperationInputDefinition> inputDefinitionListDataDefinition = operation.getInputs(); - if (inputDefinitionListDataDefinition == null) { - return Either.left(Boolean.TRUE); - } - List<OperationInputDefinition> inputListToscaDataDefinition = inputDefinitionListDataDefinition.getListToscaDataDefinition(); - - for(OperationInputDefinition inputDefinition : inputListToscaDataDefinition ) { - if(!validateInputExistsInComponent(inputDefinition, inputs)) { - String missingPropertyName = inputDefinition.getInputId().contains(".") ? inputDefinition.getInputId().substring(inputDefinition.getInputId().indexOf(".") + 1) : inputDefinition.getInputId(); - LOGGER.error("Interface operation input property {} not found in component input properties", missingPropertyName); - ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT, missingPropertyName); - return Either.right(inputResponse); + private Either<Boolean, Set<String>> isOutputParametersUnique(Operation operationDataDefinition) { + Set<String> outputParamNamesSet = new HashSet<>(); + Set<String> duplicateParamNamesToReturn = new HashSet<>(); + operationDataDefinition.getOutputs().getListToscaDataDefinition().forEach(outputParam -> { + if (!outputParamNamesSet.add(outputParam.getName().trim())) { + duplicateParamNamesToReturn.add(outputParam.getName().trim()); } + }); + if (!duplicateParamNamesToReturn.isEmpty()) { + return Either.right(duplicateParamNamesToReturn); } return Either.left(Boolean.TRUE); } - private boolean validateInputExistsInComponent(OperationInputDefinition input, - List<InputDefinition> inputs) { - return inputs.stream().anyMatch(inp -> inp.getUniqueId().equals(input.getInputId())) - || ((input.getInputId().contains(".") - && inputs.stream().anyMatch(inp -> inp.getUniqueId().equals( - input.getInputId().substring(0, input.getInputId().lastIndexOf(".")))))) ; - } - - private ResponseFormatManager getResponseFormatManager() { - return ResponseFormatManager.getInstance(); + private boolean isValidOperationType(String operationType) { + return Pattern.matches(TYPE_VALIDATION_REGEX, operationType); } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/InterfaceUIDataConverter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/InterfaceUIDataConverter.java deleted file mode 100644 index 7fbc56a624..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/InterfaceUIDataConverter.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ - -package org.openecomp.sdc.be.datamodel.utils; - -import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationParamDataDefinition; -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.model.Operation; - -import java.util.List; -import java.util.stream.Collectors; - -public class InterfaceUIDataConverter { - - private InterfaceUIDataConverter () { - - } - public static Operation convertInterfaceDataToOperationData(InterfaceOperationDataDefinition interfaceOperation){ - - ListDataDefinition<InterfaceOperationParamDataDefinition> inputParams = interfaceOperation.getInputParams(); - ListDataDefinition<OperationInputDefinition> inputs = new ListDataDefinition<>(); - if (inputParams != null) { - List<OperationInputDefinition> inputList = inputParams.getListToscaDataDefinition().stream() - .map(interfaceOperationParamDataDefinition -> new OperationInputDefinition( - interfaceOperationParamDataDefinition.getName(), - interfaceOperationParamDataDefinition.getProperty(), - interfaceOperationParamDataDefinition.getMandatory() == null ? false : interfaceOperationParamDataDefinition.getMandatory(), - interfaceOperationParamDataDefinition.getType() - )).collect(Collectors.toList()); - inputList.forEach(inputs::add); - } - ListDataDefinition<InterfaceOperationParamDataDefinition> outputParams = interfaceOperation.getOutputParams(); - ListDataDefinition<OperationOutputDefinition> outputs = new ListDataDefinition<>(); - if(outputParams != null) { - List<OperationOutputDefinition> outputList = outputParams.getListToscaDataDefinition().stream() - .map(interfaceOperationParamDataDefinition -> new OperationOutputDefinition( - interfaceOperationParamDataDefinition.getName(), - interfaceOperationParamDataDefinition.getMandatory() == null ? false : interfaceOperationParamDataDefinition.getMandatory(), - interfaceOperationParamDataDefinition.getType() - )).collect(Collectors.toList()); - outputList.forEach(outputs::add); - } - - Operation operationData = new Operation(); - operationData.setDescription(interfaceOperation.getDescription()); - operationData.setName(interfaceOperation.getOperationType()); - operationData.setUniqueId(interfaceOperation.getUniqueId()); - operationData.setInputs(inputs); - operationData.setOutputs(outputs); - operationData.setWorkflowId(interfaceOperation.getWorkflowId()); - operationData.setWorkflowVersionId(interfaceOperation.getWorkflowVersionId()); - operationData.setWorkflowAssociationType(interfaceOperation.getWorkflowAssociationType()); - - return operationData; - } - - public static InterfaceOperationDataDefinition convertOperationDataToInterfaceData(Operation operationData){ - ListDataDefinition<OperationInputDefinition> inputs = operationData.getInputs(); - List<InterfaceOperationParamDataDefinition> inputParamList = inputs.getListToscaDataDefinition().stream() - .map(operationInputDefinition -> new InterfaceOperationParamDataDefinition(operationInputDefinition.getName(), - operationInputDefinition.getInputId(), - operationInputDefinition.isRequired(), - operationInputDefinition.getType())).collect( - Collectors.toList()); - ListDataDefinition<InterfaceOperationParamDataDefinition> inputParams = new ListDataDefinition<>(); - inputParamList.forEach(inputParams::add); - - ListDataDefinition<OperationOutputDefinition> outputs = operationData.getOutputs(); - List<InterfaceOperationParamDataDefinition> outputParamList = outputs.getListToscaDataDefinition() - .stream().map(operationOutputDefinition -> new InterfaceOperationParamDataDefinition(operationOutputDefinition.getName(), - operationOutputDefinition.isRequired(), - operationOutputDefinition.getType())).collect(Collectors.toList()); - ListDataDefinition<InterfaceOperationParamDataDefinition> outputParams = new ListDataDefinition<>(); - outputParamList.forEach(outputParams::add); - - InterfaceOperationDataDefinition interfaceOperationDataDefinition = new InterfaceOperationDataDefinition(); - interfaceOperationDataDefinition.setUniqueId(operationData.getUniqueId()); - interfaceOperationDataDefinition.setOperationType(operationData.getName()); - interfaceOperationDataDefinition.setDescription(operationData.getDescription()); - interfaceOperationDataDefinition.setInputParams(inputParams); - interfaceOperationDataDefinition.setOutputParams(outputParams); - interfaceOperationDataDefinition.setArtifactUUID(operationData.getImplementation().getArtifactUUID()); - interfaceOperationDataDefinition.setWorkflowId(operationData.getWorkflowId()); - interfaceOperationDataDefinition.setWorkflowVersionId(operationData.getWorkflowVersionId()); - interfaceOperationDataDefinition.setWorkflowAssociationType(operationData.getWorkflowAssociationType()); - - return interfaceOperationDataDefinition; - } - -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java index 03c5e0fbf1..bc2ebbfb14 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/externalapi/servlet/ArtifactExternalServlet.java @@ -25,7 +25,6 @@ import com.jcabi.aspects.Loggable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.util.EnumMap; import java.util.HashMap; import java.util.Map; @@ -70,12 +69,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; + /** * This Servlet serves external users operations on artifacts. * @@ -98,7 +92,7 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { private static String startLog = "Start handle request of "; @POST - @Path("/{assetType}/{uuid}/interfaces/{operationUUID}/artifacts/{artifactUUID}") + @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "uploads of artifact to VF operation workflow", httpMethod = "POST", notes = "uploads of artifact to VF operation workflow") @ApiResponses(value = { @@ -127,6 +121,7 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { @ApiParam(value = "The username and password", required = true) @HeaderParam(value = Constants.AUTHORIZATION_HEADER) String authorization, @ApiParam(value = "Asset type") @PathParam("assetType") String assetType, @ApiParam(value = "The uuid of the asset as published in the metadata", required = true)@PathParam("uuid") final String uuid, + @ApiParam(value = "The uuid of the interface", required = true)@PathParam("interfaceUUID") final String interfaceUUID, @ApiParam(value = "The uuid of the operation", required = true)@PathParam("operationUUID") final String operationUUID, @ApiParam(value = "The uuid of the artifact", required = true)@PathParam("artifactUUID") final String artifactUUID, @ApiParam( hidden = true) String data) { @@ -154,7 +149,7 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum - .findByParamName(assetType), uuid, artifactUUID, operationUUID, + .findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID, resourceCommonInfo, artifactsLogic.new ArtifactOperationInfo(true, false, ArtifactOperationEnum.UPDATE)); if (uploadArtifactEither.isRight()) { log.debug(FAILED_TO_UPDATE_ARTIFACT); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java index 815f9763f9..801572d2f1 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/InterfaceOperationServlet.java @@ -16,6 +16,7 @@ package org.openecomp.sdc.be.servlets; +import com.google.common.collect.ImmutableMap; import com.jcabi.aspects.Loggable; import fj.data.Either; import io.swagger.annotations.Api; @@ -23,8 +24,12 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import java.util.Optional; -import java.util.UUID; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.inject.Singleton; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -43,10 +48,9 @@ import javax.ws.rs.core.Response; import org.openecomp.sdc.be.components.impl.InterfaceOperationBusinessLogic; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.dao.api.ActionStatus; -import org.openecomp.sdc.be.datamodel.utils.InterfaceUIDataConverter; -import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; -import org.openecomp.sdc.be.model.Operation; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; @@ -56,190 +60,270 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) -@Path("/v1/catalog/{componentType}/{componentId}/interfaceOperations") +@Path("/v1/catalog") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) -@Api(value = "Interface Operation", description = "Interface Operation Servlet") +@Api(value = "Interface Operation Servlet", description = "Interface Operation Servlet") @Singleton public class InterfaceOperationServlet extends AbstractValidationsServlet { - private static final Logger log = LoggerFactory.getLogger(InterfaceOperationServlet.class); - - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Path("/") - @ApiOperation(value = "Create Interface Operation", httpMethod = "POST", notes = "Create Interface Operation", response = InterfaceOperationDataDefinition.class) - @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Interface Operation"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 400, message = "Invalid content / Missing content"), - @ApiResponse(code = 409, message = "Interface Operation already exist")}) - public Response createInterfaceOperation( - @ApiParam(value = "Interface Operation to create", required = true) String data, - @ApiParam(value = "Component type") @PathParam("componentType") String componentType, - @ApiParam(value = "Component Id") @PathParam("componentId") String componentId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, componentType ,componentId, request, userId, false); - } - - @PUT - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Path("/") - @ApiOperation(value = "Update Interface Operation", httpMethod = "PUT", notes = "Update Interface Operation", response = InterfaceOperationDataDefinition.class) - @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Interface Operation"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 400, message = "Invalid content / Missing content")}) - public Response updateInterfaceOperation( - @ApiParam(value = "Interface Operation to update", required = true) String data, - @ApiParam(value = "Component type") @PathParam("componentType") String componentType, - @ApiParam(value = "Component Id") @PathParam("componentId") String componentId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return createOrUpdate(data, componentType,componentId, request, userId, true); - } - - @DELETE - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Path("/{interfaceOperationId}") - @ApiOperation(value = "Delete Interface Operation", httpMethod = "DELETE", notes = "Delete Interface Operation", response = InterfaceOperationDataDefinition.class) - @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Interface Operation"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 400, message = "Invalid content / Missing content")}) - public Response deleteInterfaceOperation( - @ApiParam(value = "Interface Operation Id") @PathParam("interfaceOperationId") String interfaceOperationId, - @ApiParam(value = "Component Id") @PathParam("componentId") String componentId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - return delete(interfaceOperationId, componentId, request, userId); - } - - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Path("/{interfaceOperationId}") - @ApiOperation(value = "Get Interface Operation", httpMethod = "GET", notes = "GET Interface Operation", response = InterfaceOperationDataDefinition.class) - @ApiResponses(value = {@ApiResponse(code = 201, message = "Get Interface Operation"), - @ApiResponse(code = 403, message = "Restricted operation"), - @ApiResponse(code = 400, message = "Invalid content / Missing content")}) - public Response getInterfaceOperation( - @ApiParam(value = "Interface Operation Id") @PathParam("interfaceOperationId") String interfaceOperationId, - @ApiParam(value = "Component Id") @PathParam("componentId") String componentId, - @Context final HttpServletRequest request, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId) { - - return get(interfaceOperationId, componentId, request, userId); - } - - private Response get (String interfaceOperationId, String componentId, HttpServletRequest request, String userId){ - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("Start get request of {} with modifier id {}", url, userId); - - try { - String componentIdLower = componentId.toLowerCase(); - InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context); - - Either<Operation, ResponseFormat> actionResponse = businessLogic.getInterfaceOperation(componentIdLower, interfaceOperationId, modifier, true); - if (actionResponse.isRight()) { - log.error("failed to get interface operation"); - return buildErrorResponse(actionResponse.right().value()); - } - - InterfaceOperationDataDefinition interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(actionResponse.left().value()); - Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + private static final Logger log = LoggerFactory.getLogger(InterfaceOperationServlet.class); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/resources/{resourceId}/interfaceOperations") + @ApiOperation(value = "Create Interface Operations on Resource", httpMethod = "POST", + notes = "Create Interface Operations on Resource", response = InterfaceDefinition.class, responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Interface Operations on Resource"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Resource not found"), + @ApiResponse(code = 409, message = "Interface Operation already exist")}) + public Response createInterfaceOperationsOnResource( + @ApiParam(value = "Interface Operations to create", required = true) String data, + @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, false); + } + + private Response createOrUpdate(String data, ComponentTypeEnum componentType, String componentId, + HttpServletRequest request, String userId, boolean isUpdate) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("Start create or update request of {} with modifier id {}", url, userId); + + try { + String componentIdLower = componentId.toLowerCase(); + InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context); + + List<InterfaceDefinition> mappedInterfaceData = getMappedInterfaceData(data, modifier, componentType); + Either<List<InterfaceDefinition>, ResponseFormat> actionResponse; + if (isUpdate) { + actionResponse = + businessLogic.updateInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true); + } else { + actionResponse = + businessLogic.createInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true); + } + + if (actionResponse.isRight()) { + log.error("failed to create or update interface operation"); + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + getFormattedResponse(actionResponse.left().value())); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Interface Operation Creation or update"); + log.error("create or update interface Operation with an error", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } + } + + private List<InterfaceDefinition> getMappedInterfaceData(String inputJson, User user, + ComponentTypeEnum componentTypeEnum) { + Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither = + getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user, + UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); + return new ArrayList<>(uiComponentEither.left().value().getInterfaces().values()); } - catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component interface operations"); - log.error("get component interface operations failed with exception", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + private Object getFormattedResponse(List<InterfaceDefinition> interfaceDefinitions) throws IOException { + Map<String, List<InterfaceDefinition>> allInterfaces = + ImmutableMap.of(JsonPresentationFields.INTERFACES.getPresentation(), interfaceDefinitions); + return RepresentationUtils.toFilteredRepresentation(allInterfaces); } - } - private Response delete (String interfaceOperationId, String componentId, HttpServletRequest - request, String userId){ + @PUT + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/resources/{resourceId}/interfaceOperations") + @ApiOperation(value = "Update Interface Operations on Resource", httpMethod = "PUT", + notes = "Update Interface Operations on Resource", response = InterfaceDefinition.class, responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Interface Operations on Resource"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Resource not found")}) + public Response updateInterfaceOperationsOnResource( + @ApiParam(value = "Interface Operations to update", required = true) String data, + @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + return createOrUpdate(data, ComponentTypeEnum.RESOURCE, resourceId, request, userId, true); + } + + @DELETE + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}") + @ApiOperation(value = "Delete Interface Operation from Resource", httpMethod = "DELETE", + notes = "Delete Interface Operation from Resource", response = InterfaceDefinition.class, responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Interface Operation from Resource"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Resource not found")}) + public Response deleteInterfaceOperationsFromResource( + @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId, + @ApiParam(value = "Interface Id") @PathParam("interfaceId") String interfaceId, + @ApiParam(value = "Operation Id") @PathParam("operationIds") String operationId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + return delete(interfaceId, operationId, resourceId, request, userId); + } - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); + private Response delete(String interfaceId, String operationIds, String componentId, HttpServletRequest request, + String userId) { - User modifier = new User(); - modifier.setUserId(userId); - log.debug("Start delete request of {} with modifier id {}", url, userId); + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); - try { - String componentIdLower = componentId.toLowerCase(); - InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context); + User modifier = new User(); + modifier.setUserId(userId); + log.debug("Start delete request of {} with modifier id {}", url, userId); - Either<Operation, ResponseFormat> actionResponse = businessLogic.deleteInterfaceOperation(componentIdLower, interfaceOperationId, modifier, true); - if (actionResponse.isRight()) { - log.error("failed to delete interface operation"); - return buildErrorResponse(actionResponse.right().value()); - } + try { + String componentIdLower = componentId.toLowerCase(); + InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context); - InterfaceOperationDataDefinition interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(actionResponse.left().value()); - Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + List<String> operationsToDelete = + Stream.of(operationIds.split(",")).map(String::trim).collect(Collectors.toList()); + Either<List<InterfaceDefinition>, ResponseFormat> actionResponse = businessLogic.deleteInterfaceOperation( + componentIdLower, interfaceId, operationsToDelete, modifier, true); + if (actionResponse.isRight()) { + log.error("failed to delete interface operation"); + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + getFormattedResponse(actionResponse.left().value())); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Interface Operation"); + log.error("Delete interface operation with an error", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } } - catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Interface Operation"); - log.error("Delete interface operation with an error", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationId}") + @ApiOperation(value = "Get Interface Operation from Resource", httpMethod = "GET", + notes = "GET Interface Operation from Resource", response = InterfaceDefinition.class, responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Interface Operation from Resource"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Resource not found")}) + public Response getInterfaceOperationsFromResource( + @ApiParam(value = "Resource Id") @PathParam("resourceId") String resourceId, + @ApiParam(value = "Interface Id") @PathParam("interfaceId") String interfaceId, + @ApiParam(value = "Operation Id") @PathParam("operationId") String operationId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + return get(interfaceId, operationId, resourceId, request, userId); } - } - - private Response createOrUpdate (String data, String componentType, String componentId, HttpServletRequest request, String userId, boolean isUpdate) { - ServletContext context = request.getSession().getServletContext(); - String url = request.getMethod() + " " + request.getRequestURI(); - - User modifier = new User(); - modifier.setUserId(userId); - log.debug("Start create or update request of {} with modifier id {}", url, userId); - - try { - String componentIdLower = componentId.toLowerCase(); - InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context); - - Operation operation = getMappedOperationData(data, isUpdate, modifier, ComponentTypeEnum.findByParamName(componentType)); - Either<Operation, ResponseFormat> actionResponse ; - if (isUpdate) { - actionResponse = businessLogic.updateInterfaceOperation(componentIdLower, operation, modifier, true); - } else { - actionResponse = businessLogic.createInterfaceOperation(componentIdLower, operation, modifier, true); - } - - if (actionResponse.isRight()) { - log.error("failed to update or create interface operation"); - return buildErrorResponse(actionResponse.right().value()); - } - - InterfaceOperationDataDefinition interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(actionResponse.left().value()); - Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition); - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); + + private Response get(String interfaceId, String operationIds, String componentId, HttpServletRequest request, + String userId) { + ServletContext context = request.getSession().getServletContext(); + String url = request.getMethod() + " " + request.getRequestURI(); + + User modifier = new User(); + modifier.setUserId(userId); + log.debug("Start get request of {} with modifier id {}", url, userId); + + try { + String componentIdLower = componentId.toLowerCase(); + InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context); + + List<String> operationsToGet = + Stream.of(operationIds.split(",")).map(String::trim).collect(Collectors.toList()); + Either<List<InterfaceDefinition>, ResponseFormat> actionResponse = + businessLogic.getInterfaceOperation(componentIdLower, interfaceId, operationsToGet, modifier, true); + if (actionResponse.isRight()) { + log.error("failed to get interface operation"); + return buildErrorResponse(actionResponse.right().value()); + } + + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), + getFormattedResponse(actionResponse.left().value())); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component interface operations"); + log.error("get component interface operations failed with exception", e); + return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + } } - catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Interface Operation Creation or update"); - log.error("create or update interface Operation with an error", e); - return buildErrorResponse(getComponentsUtils().getResponseFormat(ActionStatus.GENERAL_ERROR)); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/services/{serviceId}/interfaceOperations") + @ApiOperation(value = "Create Interface Operations on Service", httpMethod = "POST", + notes = "Create Interface Operations on Service", response = InterfaceDefinition.class, responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Create Interface Operations on Service"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Service not found"), + @ApiResponse(code = 409, message = "Interface Operation already exist")}) + public Response createInterfaceOperationsOnService( + @ApiParam(value = "Interface Operations to create", required = true) String data, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, false); + } + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/services/{serviceId}/interfaceOperations") + @ApiOperation(value = "Update Interface Operations on Service", httpMethod = "PUT", + notes = "Update Interface Operations on Service", response = InterfaceDefinition.class, responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Update Interface Operations on Service"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Service not found")}) + public Response updateInterfaceOperationsOnService( + @ApiParam(value = "Interface Operations to update", required = true) String data, + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + return createOrUpdate(data, ComponentTypeEnum.SERVICE, serviceId, request, userId, true); } - } - - private Operation getMappedOperationData(String inputJson, boolean isUpdate, User user, ComponentTypeEnum componentTypeEnum){ - Either<UiComponentDataTransfer, ResponseFormat> uiComponentEither = getComponentsUtils().convertJsonToObjectUsingObjectMapper(inputJson, user, UiComponentDataTransfer.class, AuditingActionEnum.CREATE_RESOURCE, componentTypeEnum); - Optional<InterfaceOperationDataDefinition> opDef = uiComponentEither.left().value().getInterfaceOperations().values().stream().findFirst(); - InterfaceOperationDataDefinition interfaceOperationDataDefinition = new InterfaceOperationDataDefinition(); - if(opDef.isPresent()) { - interfaceOperationDataDefinition = opDef.get(); - if(!isUpdate) - interfaceOperationDataDefinition.setUniqueId(UUID.randomUUID().toString()); + + @DELETE + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}") + @ApiOperation(value = "Delete Interface Operation from Service", httpMethod = "DELETE", + notes = "Delete Interface Operation from Service", response = InterfaceDefinition.class, responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Delete Interface Operation from Service"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Service not found")}) + public Response deleteInterfaceOperationsFromService( + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @ApiParam(value = "Interface Id") @PathParam("interfaceId") String interfaceId, + @ApiParam(value = "Operation Id") @PathParam("operationId") String operationId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + return delete(interfaceId, operationId, serviceId, request, userId); + } + + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Path("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationId}") + @ApiOperation(value = "Get Interface Operation from Service", httpMethod = "GET", + notes = "GET Interface Operation from Service", response = InterfaceDefinition.class, responseContainer = "List") + @ApiResponses(value = {@ApiResponse(code = 201, message = "Get Interface Operation from Service"), + @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @ApiResponse(code = 403, message = "Restricted operation"), + @ApiResponse(code = 404, message = "Service not found")}) + public Response getInterfaceOperationsFromService( + @ApiParam(value = "Service Id") @PathParam("serviceId") String serviceId, + @ApiParam(value = "Interface Id") @PathParam("interfaceId") String interfaceId, + @ApiParam(value = "Operation Id") @PathParam("operationId") String operationId, + @HeaderParam(value = Constants.USER_ID_HEADER) String userId, @Context final HttpServletRequest request) { + return get(interfaceId, operationId, serviceId, request, userId); } - return InterfaceUIDataConverter.convertInterfaceDataToOperationData(interfaceOperationDataDefinition); - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java index dbdfaa9897..0358e67075 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/servlets/RepresentationUtils.java @@ -20,7 +20,6 @@ package org.openecomp.sdc.be.servlets; - import com.fasterxml.jackson.annotation.JsonFilter; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -32,20 +31,22 @@ import com.google.common.collect.ImmutableMap; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import org.openecomp.sdc.be.config.BeEcompErrorManager; -import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationDataDefinition; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.IOException; -import java.util.*; - public class RepresentationUtils { private static final Logger log = Logger.getLogger(RepresentationUtils.class); @@ -188,11 +189,8 @@ public class RepresentationUtils { .put(ArrayList.class,IsEmptyFilterMixIn.class) .put(HashSet.class,IsEmptyFilterMixIn.class) .put(InterfaceDefinition.class,IsEmptyFilterMixIn.class) - .put(Operation.class,IsEmptyFilterMixIn.class) .put(Resource.class,IsEmptyFilterMixIn.class) .put(ToscaDataDefinition.class,IsEmptyFilterMixIn.class) - .put(InterfaceOperationDataDefinition.class,IsEmptyFilterMixIn.class).build(); - - + .build(); } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java index 69c4cec42b..6d344f78e5 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/ToscaExportHandler.java @@ -45,6 +45,7 @@ import org.openecomp.sdc.be.model.ComponentParametersView; import org.openecomp.sdc.be.model.DataTypeDefinition; import org.openecomp.sdc.be.model.GroupInstance; import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.RelationshipInfo; import org.openecomp.sdc.be.model.RequirementCapabilityRelDef; @@ -55,7 +56,9 @@ import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; +import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; import org.openecomp.sdc.be.tosca.model.ToscaCapability; import org.openecomp.sdc.be.tosca.model.ToscaGroupTemplate; @@ -70,6 +73,7 @@ import org.openecomp.sdc.be.tosca.model.ToscaTopolgyTemplate; import org.openecomp.sdc.be.tosca.utils.ForwardingPathToscaUtil; import org.openecomp.sdc.be.tosca.utils.InputConverter; import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.exception.ResponseFormat; import org.springframework.beans.factory.annotation.Autowired; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.DumperOptions.FlowStyle; @@ -112,11 +116,12 @@ public class ToscaExportHandler { private GroupExportParser groupExportParser; private PropertyConvertor propertyConvertor; private InputConverter inputConverter; + private InterfaceLifecycleOperation interfaceLifecycleOperation; @Autowired public ToscaExportHandler(ApplicationDataTypeCache dataTypeCache, ToscaOperationFacade toscaOperationFacade, CapabilityRequirementConverter capabilityRequirementConverter, PolicyExportParser policyExportParser, - GroupExportParser groupExportParser, InputConverter inputConverter) { + GroupExportParser groupExportParser, InputConverter inputConverter, InterfaceLifecycleOperation interfaceLifecycleOperation) { this.dataTypeCache = dataTypeCache; this.toscaOperationFacade = toscaOperationFacade; this.capabilityRequirementConverter = capabilityRequirementConverter; @@ -124,6 +129,7 @@ public class ToscaExportHandler { this.groupExportParser = groupExportParser; this.propertyConvertor = PropertyConvertor.getInstance(); this.inputConverter = inputConverter; + this.interfaceLifecycleOperation = interfaceLifecycleOperation; } @@ -553,7 +559,20 @@ public class ToscaExportHandler { boolean isAssociatedResourceComponent) { log.debug("start convert node type for {}", component.getUniqueId()); ToscaNodeType toscaNodeType = createNodeType(component); - toscaNode.setInterface_types(addInterfaceTypeElement(component)); + + Either<Map<String, InterfaceDefinition>, StorageOperationStatus> lifecycleTypeEither = + interfaceLifecycleOperation.getAllInterfaceLifecycleTypes(); + if(lifecycleTypeEither.isRight()){ + log.debug("Failed to fetch all interface types :", lifecycleTypeEither.right().value()); + return Either.right(ToscaError.GENERAL_ERROR); + } + List<String> allGlobalInterfaceTypes = lifecycleTypeEither.left().value() + .values() + .stream() + .map(interfaceDef -> interfaceDef.getType()) + .collect(Collectors.toList()); + toscaNode.setInterface_types(addInterfaceTypeElement(component, allGlobalInterfaceTypes)); + Either<Map<String, DataTypeDefinition>, TitanOperationStatus> dataTypesEither = dataTypeCache.getAll(); if (dataTypesEither.isRight()) { log.debug("Failed to fetch all data types :", dataTypesEither.right().value()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtil.java b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtil.java index 7afad74f64..fbef11d2e8 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtil.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtil.java @@ -60,7 +60,7 @@ public class InterfacesOperationsToscaUtil { * @param component to work on * @return the added element */ - public static Map<String, Object> addInterfaceTypeElement(Component component) { + public static Map<String, Object> addInterfaceTypeElement(Component component, List<String> allInterfaceTypes) { if (component instanceof Product) { return null; } @@ -68,24 +68,28 @@ public class InterfacesOperationsToscaUtil { if (MapUtils.isEmpty(interfaces)) { return null; } + Map<String, Object> toscaInterfaceTypes = new HashMap<>(); for (InterfaceDefinition interfaceDefinition : interfaces.values()) { - ToscaInterfaceNodeType toscaInterfaceType = new ToscaInterfaceNodeType(); - toscaInterfaceType.setDerived_from(DERIVED_FROM_STANDARD_INTERFACE); + boolean isInterfaceTypeExistInGlobalType = + allInterfaceTypes.stream().anyMatch(type -> type.equalsIgnoreCase(interfaceDefinition.getType())); + if (!isInterfaceTypeExistInGlobalType) { + ToscaInterfaceNodeType toscaInterfaceType = new ToscaInterfaceNodeType(); + toscaInterfaceType.setDerived_from(DERIVED_FROM_STANDARD_INTERFACE); - final Map<String, OperationDataDefinition> operations = interfaceDefinition.getOperations(); - Map<String, Object> toscaOperations = new HashMap<>(); + final Map<String, OperationDataDefinition> operations = interfaceDefinition.getOperations(); + Map<String, Object> toscaOperations = new HashMap<>(); - for (Map.Entry<String, OperationDataDefinition> operationEntry : operations.entrySet()) { - toscaOperations.put(operationEntry.getValue().getName(), - null); //currently not initializing any of the operations' fields as it is not needed - } - toscaInterfaceType.setOperations(toscaOperations); - Map<String, Object> interfacesAsMap = getObjectAsMap(toscaInterfaceType); - Map<String, Object> operationsMap = (Map<String, Object>) interfacesAsMap.remove(OPERATIONS_KEY); - interfacesAsMap.putAll(operationsMap); + for (Map.Entry<String, OperationDataDefinition> operationEntry : operations.entrySet()) { + toscaOperations.put(operationEntry.getValue().getName(), null); + } + toscaInterfaceType.setOperations(toscaOperations); + Map<String, Object> interfacesAsMap = getObjectAsMap(toscaInterfaceType); + Map<String, Object> operationsMap = (Map<String, Object>) interfacesAsMap.remove(OPERATIONS_KEY); + interfacesAsMap.putAll(operationsMap); - toscaInterfaceTypes.put(interfaceDefinition.getToscaResourceName(), interfacesAsMap); + toscaInterfaceTypes.put(interfaceDefinition.getType(), interfacesAsMap); + } } return MapUtils.isNotEmpty(toscaInterfaceTypes) ? toscaInterfaceTypes : null; } @@ -108,8 +112,8 @@ public class InterfacesOperationsToscaUtil { Map<String, Object> toscaInterfaceDefinitions = new HashMap<>(); for (InterfaceDefinition interfaceDefinition : interfaces.values()) { ToscaInterfaceDefinition toscaInterfaceDefinition = new ToscaInterfaceDefinition(); - final String toscaResourceName = interfaceDefinition.getToscaResourceName(); - toscaInterfaceDefinition.setType(toscaResourceName); + final String interfaceType = interfaceDefinition.getType(); + toscaInterfaceDefinition.setType(interfaceType); final Map<String, OperationDataDefinition> operations = interfaceDefinition.getOperations(); Map<String, Object> toscaOperations = new HashMap<>(); @@ -133,7 +137,7 @@ public class InterfacesOperationsToscaUtil { Map<String, Object> operationsMap = (Map<String, Object>) interfaceDefAsMap.remove(OPERATIONS_KEY); handleDefaults(operationsMap); interfaceDefAsMap.putAll(operationsMap); - toscaInterfaceDefinitions.put(getLastPartOfName(toscaResourceName), interfaceDefAsMap); + toscaInterfaceDefinitions.put(getLastPartOfName(interfaceType), interfaceDefAsMap); } if (MapUtils.isNotEmpty(toscaInterfaceDefinitions)) { nodeType.setInterfaces(toscaInterfaceDefinitions); @@ -141,8 +145,8 @@ public class InterfacesOperationsToscaUtil { } /*** - * workaround for : currently "defaultp" is not being converted to "default" by the relevant code in ToscaExportHandler - * so, any string Map key named "defaultp" will have its named changed to "default" + * workaround for : currently "defaultp" is not being converted to "default" by the relevant code in + * ToscaExportHandler so, any string Map key named "defaultp" will have its named changed to "default" * @param operationsMap the map to update */ private static void handleDefaults(Map<String, Object> operationsMap) { diff --git a/catalog-be/src/main/resources/config/error-configuration.yaml b/catalog-be/src/main/resources/config/error-configuration.yaml index 84213bbe8d..ff86aff820 100644 --- a/catalog-be/src/main/resources/config/error-configuration.yaml +++ b/catalog-be/src/main/resources/config/error-configuration.yaml @@ -2033,7 +2033,7 @@ errors: #---------SVC4695----------------------------- # %1 - Interface Operation Name INTERFACE_OPERATION_NAME_ALREADY_IN_USE: { - code: 400, + code: 409, message: "Error: Interface Operation name '%1' already in use, Your current changes will not be saved.", messageId: "SVC4695" } @@ -2041,20 +2041,20 @@ errors: # %1 - Interface Operation Name INTERFACE_OPERATION_NAME_INVALID: { code: 400, - message: "Error: Interface Operation name '%1' is Invalid, Operation name should not contain special character, space, numbers and should not be greater than 200 characters.", + message: "Error: Interface Operation name '%1' is Invalid, Operation name should not contain special character, space and should not be greater than 200 characters.", messageId: "SVC4696" } #---------SVC4697----------------------------- INTERFACE_OPERATION_NAME_MANDATORY: { - code: 404, + code: 400, message: "Error: Interface Operation name is mandatory, Operation name can't be empty.", messageId: "SVC4697" } #---------SVC4698----------------------------- -# %1 - Interface Operation description - INTERFACE_OPERATION_DESCRIPTION_MAX_LENGTH: { +# %1 - Interface type + INTERFACE_OPERATION_INVALID_FOR_LOCAL_TYPE: { code: 400, - message: "Error: Interface Operation description '%1' is invalid, maximum 200 characters allowed.", + message: "Error: Invalid input, only one operation is allowed in local interface type '%1'.", messageId: "SVC4698" } #---------SVC4699----------------------------- @@ -2066,20 +2066,20 @@ errors: } #---------SVC4700----------------------------- INTERFACE_OPERATION_INPUT_NAME_MANDATORY: { - code: 404, + code: 400, message: "Error: Interface operation input parameter name should not be empty.", messageId: "SVC4700" } #---------SVC4701----------------------------- -# %1 - resource Id +# %1 - component Id INTERFACE_OPERATION_NOT_FOUND: { code: 404, - message: "Error: Interface operation not found in the resource '%1'.", + message: "Error: Interface operation not found in the component '%1'.", messageId: "SVC4701" } #---------SVC4702----------------------------- INTERFACE_OPERATION_NOT_DELETED: { - code: 404, + code: 400, message: "Error: Failed to delete interface operation.", messageId: "SVC4702" } @@ -2133,29 +2133,43 @@ errors: message: "Error: CSAR packaging failed for %1 %2.", messageId: "SVC4706" } -#---------SVC4704----------------------------- -# %1 - Interface Operation input property name +#---------SVC4708----------------------------- +# %1 - Interface Operation input property name, component type INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT: { code: 404, - message: "Error: Interface operation input parameter property '%1' not found in component input properties.", - messageId: "SVC4704" + message: "Error: Interface operation input parameter property '%1' not found in '%2' input properties.", + messageId: "SVC4708" } -#---------SVC4705----------------------------- +#---------SVC4709----------------------------- # %1 - Interface Operation output parameter name INTERFACE_OPERATION_OUTPUT_NAME_ALREADY_IN_USE: { code: 400, message: "Error: Interface Operation output parameter name '%1' already in use, Your current changes will not be saved.", - messageId: "SVC4705" + messageId: "SVC4708" } -#---------SVC4706----------------------------- +#---------SVC4710----------------------------- INTERFACE_OPERATION_OUTPUT_NAME_MANDATORY: { - code: 404, + code: 400, message: "Error: Interface operation output parameter name should not be empty.", - messageId: "SVC4706" + messageId: "SVC4710" + } +#---------SVC4711----------------------------- +# %1 - interface Id + INTERFACE_NOT_FOUND_IN_COMPONENT: { + code: 404, + message: "Error: Interface not found in the component '%1'.", + messageId: "SVC4711" } #---------SVC4712----------------------------- INTERFACE_LIFECYCLE_TYPES_NOT_FOUND: { code: 404, message: "Error: Interface Lifecycle types not found.", messageId: "SVC4712" + } +#---------SVC4713----------------------------- +# %1 - Interface Operation Name + INTERFACE_OPERATION_INVALID_FOR_GLOBAL_TYPE: { + code: 400, + message: "Error: Invalid input, only pre-defined operation names are allowed in global interface type '%1'", + messageId: "SVC4713" }
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java index 1e6370e095..2ef3d463eb 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InputsBusinessLogicTest.java @@ -67,9 +67,6 @@ public class InputsBusinessLogicTest { @Mock private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - @Mock - private ComponentInstanceBusinessLogic componentInstanceBusinessLogic; - @InjectMocks private InputsBusinessLogic testInstance; diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java index f2d8b57dbf..8509f3e749 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java @@ -18,432 +18,399 @@ package org.openecomp.sdc.be.components.impl; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import fj.data.Either; -import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.servlet.ServletContext; import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.ElementOperationMock; -import org.openecomp.sdc.be.auditing.impl.AuditingManager; +import org.mockito.junit.MockitoJUnitRunner; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; import org.openecomp.sdc.be.components.validation.InterfaceOperationValidation; import org.openecomp.sdc.be.components.validation.UserValidations; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; import org.openecomp.sdc.be.dao.jsongraph.TitanDao; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; -import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.impl.ComponentsUtils; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.LifecycleStateEnum; -import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; -import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; -import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; -import org.openecomp.sdc.be.model.operations.api.IElementOperation; -import org.openecomp.sdc.be.model.operations.api.IPropertyOperation; +import org.openecomp.sdc.be.model.operations.api.IGraphLockOperation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; -import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; -import org.openecomp.sdc.be.user.Role; -import org.openecomp.sdc.be.user.UserBusinessLogic; -import org.openecomp.sdc.common.api.ConfigurationSource; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.impl.ExternalConfiguration; -import org.openecomp.sdc.common.impl.FSConfigurationSource; import org.openecomp.sdc.exception.ResponseFormat; import org.openecomp.sdc.test.utils.InterfaceOperationTestUtils; -import org.springframework.web.context.WebApplicationContext; +@RunWith(MockitoJUnitRunner.class) public class InterfaceOperationBusinessLogicTest { - private static final String RESOURCE_CATEGORY1 = "Network Layer 2-3"; - private static final String RESOURCE_SUBCATEGORY = "Router"; - - private final String resourceId = "resourceId1"; - private final String operationId = "uniqueId1"; - private Operation operation; - + private static final String resourceId = "resourceId"; + private static final String interfaceId = "interfaceId"; + private static final String operationId = "operationId"; + private static final String inputId = "inputId"; private static final String RESOURCE_NAME = "Resource1"; - - private final ServletContext servletContext = Mockito.mock(ServletContext.class); - private final TitanDao mockTitanDao = Mockito.mock(TitanDao.class); - private final UserBusinessLogic mockUserAdmin = Mockito.mock(UserBusinessLogic.class); - private final ToscaOperationFacade toscaOperationFacade = Mockito.mock(ToscaOperationFacade.class); - private final NodeTypeOperation nodeTypeOperation = Mockito.mock(NodeTypeOperation.class); - private final NodeTemplateOperation nodeTemplateOperation = Mockito.mock(NodeTemplateOperation.class); - private final TopologyTemplateOperation topologyTemplateOperation = Mockito.mock(TopologyTemplateOperation.class); - private final IPropertyOperation propertyOperation = Mockito.mock(IPropertyOperation.class); - private final ApplicationDataTypeCache applicationDataTypeCache = Mockito.mock(ApplicationDataTypeCache.class); - private final WebAppContextWrapper webAppContextWrapper = Mockito.mock(WebAppContextWrapper.class); - private final UserValidations userValidations = Mockito.mock(UserValidations.class); - private final WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); - private final ArtifactCassandraDao artifactCassandraDao = Mockito.mock(ArtifactCassandraDao.class); - private final InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.class); - private final InterfaceOperationValidation operationValidator = Mockito.mock(InterfaceOperationValidation.class); - private InterfaceLifecycleOperation interfaceLifecycleOperation = Mockito.mock(InterfaceLifecycleOperation.class); - - private final GraphLockOperation graphLockOperation = Mockito.mock(GraphLockOperation.class); - private User user = null; - private final ArtifactsBusinessLogic artifactManager = new ArtifactsBusinessLogic(); - + private static final String operationId1 = "operationId1"; + private static final String interfaceId1 = "interfaceId1"; @InjectMocks - private - InterfaceOperationBusinessLogic bl = new InterfaceOperationBusinessLogic(); + private InterfaceOperationBusinessLogic interfaceOperationBusinessLogic; + @Mock + private UserValidations userValidations; + @Mock + private ToscaOperationFacade toscaOperationFacade; + @Mock + private ComponentsUtils componentsUtils; + @Mock + private IGraphLockOperation graphLockOperation; + @Mock + private TitanDao titanDao; + @Mock + private InterfaceLifecycleOperation interfaceLifecycleOperation; + @Mock + private InterfaceOperationValidation interfaceOperationValidation; + @Mock + private InterfaceOperation interfaceOperation; + @Mock + private ArtifactCassandraDao artifactCassandraDao; + private User user; + private Resource resource; @Before public void setup() { - MockitoAnnotations.initMocks(this); - Mockito.reset(propertyOperation); + resource = new ResourceBuilder().setComponentType(ComponentTypeEnum.RESOURCE).setUniqueId(resourceId) + .setName(RESOURCE_NAME).build(); + resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceId, operationId)); + resource.setInputs(createInputsForResource()); - ExternalConfiguration.setAppName("catalog-be"); - - // init Configuration - String appConfigDir = "src/test/resources/config/catalog-be"; - ConfigurationSource configurationSource = new FSConfigurationSource(ExternalConfiguration.getChangeListener(), appConfigDir); - ConfigurationManager configurationManager = new ConfigurationManager(configurationSource); - ComponentsUtils componentsUtils = new ComponentsUtils(Mockito.mock(AuditingManager.class)); + user = new User(); + when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(true))).thenReturn(user); + when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); + when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource))) + .thenReturn(StorageOperationStatus.OK); + when(interfaceOperationValidation + .validateInterfaceOperations(anyObject(), anyObject(), any(), anyMap(), anyBoolean())) + .thenReturn(Either.left(true)); + when(titanDao.commit()).thenReturn(TitanOperationStatus.OK); + } - // Elements - IElementOperation mockElementDao = new ElementOperationMock(); + private List<InputDefinition> createInputsForResource() { + InputDefinition inputDefinition = new InputDefinition(); + inputDefinition.setName(inputId); + inputDefinition.setInputId(inputId); + inputDefinition.setUniqueId(inputId); + inputDefinition.setValue(inputId); + inputDefinition.setDefaultValue(inputId); + return Arrays.asList(inputDefinition); + } - // User data and management - user = new User(); - user.setUserId("jh0003"); - user.setFirstName("Jimmi"); - user.setLastName("Hendrix"); - user.setRole(Role.ADMIN.name()); - - Either<User, ActionStatus> eitherGetUser = Either.left(user); - when(mockUserAdmin.getUser("jh0003", false)).thenReturn(eitherGetUser); - when(userValidations.validateUserExists(eq(user.getUserId()), anyString(), eq(false))).thenReturn(user); - when(userValidations.validateUserNotEmpty(eq(user), anyString())).thenReturn(user); - // Servlet Context attributes - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(servletContext.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR)).thenReturn(webAppContextWrapper); - when(webAppContextWrapper.getWebAppContext(servletContext)).thenReturn(webAppContext); - when(webAppContext.getBean(IElementOperation.class)).thenReturn(mockElementDao); - - Either<Boolean, StorageOperationStatus> eitherFalse = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("Root", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherFalse); - - Either<Boolean, StorageOperationStatus> eitherCountExist = Either.left(true); - when(toscaOperationFacade.validateComponentNameExists("alreadyExists", ResourceTypeEnum.VFC, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCountExist); - - Either<Boolean, StorageOperationStatus> eitherCount = Either.left(false); - when(toscaOperationFacade.validateComponentNameExists(eq(RESOURCE_NAME), any(ResourceTypeEnum.class), eq(ComponentTypeEnum.RESOURCE))).thenReturn(eitherCount); - - Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); - when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); - - Either<Boolean, StorageOperationStatus> validateDerivedNotExists = Either.left(false); - when(toscaOperationFacade.validateToscaResourceNameExists("kuku")).thenReturn(validateDerivedNotExists); - when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - when(graphLockOperation.lockComponentByName(Mockito.anyString(), eq(NodeTypeEnum.Resource))).thenReturn(StorageOperationStatus.OK); - - // createResource - Resource resourceResponse = createResourceObject(true); - Either<Resource, StorageOperationStatus> eitherCreate = Either.left(resourceResponse); - when(toscaOperationFacade.createToscaComponent(any(Resource.class))).thenReturn(eitherCreate); - //TODO Remove if passes - /*when(toscaOperationFacade.validateCsarUuidUniqueness(Mockito.anyString())).thenReturn(eitherValidate);*/ - Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>(); - when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); - - //InterfaceOperation - when(operationValidator.validateInterfaceOperations(anyCollection(), anyObject(), anyBoolean())).thenReturn(Either.left(true)); - when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK); - - // BL object - artifactManager.setNodeTemplateOperation(nodeTemplateOperation); - bl = new InterfaceOperationBusinessLogic(); - - bl.setUserAdmin(mockUserAdmin); - bl.setComponentsUtils(componentsUtils); - bl.setGraphLockOperation(graphLockOperation); - bl.setTitanGenericDao(mockTitanDao); - toscaOperationFacade.setNodeTypeOperation(nodeTypeOperation); - toscaOperationFacade.setTopologyTemplateOperation(topologyTemplateOperation); - bl.setToscaOperationFacade(toscaOperationFacade); - bl.setUserValidations(userValidations); - bl.setInterfaceOperation(interfaceOperation); - bl.setInterfaceOperationValidation(operationValidator); - bl.setInterfaceLifecycleOperation(interfaceLifecycleOperation); - Resource resourceCsar = createResourceObjectCsar(true); - setCanWorkOnResource(resourceCsar); - Either<Component, StorageOperationStatus> oldResourceRes = Either.left(resourceCsar); - when(toscaOperationFacade.getToscaFullElement(resourceCsar.getUniqueId())).thenReturn(oldResourceRes); + @Test + public void createInterfaceOperationTestOnExistingInterface() { + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + when(interfaceOperation.updateInterfaces(any(), any())).thenReturn(Either.left( + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId)))); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperationEither = + interfaceOperationBusinessLogic.createInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); + Assert.assertTrue(interfaceOperationEither.isLeft()); } @Test - public void createInterfaceOperationTest() { - Resource resource = createResourceForInterfaceOperation(); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - operation = InterfaceOperationTestUtils.createMockOperation(); - when(interfaceOperation.addInterfaceOperation(any(), any(), any())).thenReturn(Either.left(InterfaceOperationTestUtils.mockOperationToReturn())); + public void createInterfaceOperationWithoutInterfaceTest() { + resource.getInterfaces().clear(); + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + when(interfaceOperation.addInterfaces(any(), any())).thenReturn(Either.left( + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId)))); + when(interfaceOperation.updateInterfaces(any(), any())).thenReturn(Either.left( + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId)))); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperationEither = + interfaceOperationBusinessLogic.createInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); + Assert.assertTrue(interfaceOperationEither.isLeft()); + } - Either<Operation, ResponseFormat> interfaceOperation = bl.createInterfaceOperation(resourceId, operation, user, true); - Assert.assertTrue(interfaceOperation.isLeft()); - Assert.assertNotNull(interfaceOperation.left().value().getWorkflowId()); - Assert.assertNotNull(interfaceOperation.left().value().getWorkflowVersionId()); + @Test + public void createInterfaceOperationWithoutInterfaceTestFail() { + resource.getInterfaces().clear(); + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + when(interfaceOperation.addInterfaces(any(), any())) + .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperationEither = + interfaceOperationBusinessLogic.createInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); + Assert.assertTrue(interfaceOperationEither.isRight()); } @Test - public void createInterfaceOperationWithoutInterfaceTest() { - Resource resource = createResourceObjectCsar(true); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - resource.setInterfaces(new HashMap<>()); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - operation = InterfaceOperationTestUtils.createMockOperation(); - when(interfaceOperation.addInterfaceOperation(any(), any(), any())).thenReturn(Either.left(InterfaceOperationTestUtils.mockOperationToReturn())); - when(interfaceOperation.addInterface(anyString(), any())).thenReturn(Either.left(new InterfaceDefinition())); + public void shouldFailWhenCreateInterfaceOperationFailedTest() { + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + when(interfaceOperation.updateInterfaces(any(), any())) + .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + Assert.assertTrue(interfaceOperationBusinessLogic.createInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId)), + user, true).isRight()); + } - Either<Operation, ResponseFormat> interfaceOperation = bl.createInterfaceOperation(resourceId, operation, user, true); + @Test + public void updateInterfaceOperationTestWithArtifactSuccess() { + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + when(artifactCassandraDao.getCountOfArtifactById(any(String.class))).thenReturn(Either.left(new Long(1))); + when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.OK); + when(interfaceOperation.updateInterfaces(any(), any())).thenReturn(Either.left( + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId)))); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperation = + interfaceOperationBusinessLogic.updateInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); Assert.assertTrue(interfaceOperation.isLeft()); + } + @Test + public void updateInterfaceOperationTestWithArtifactFailure() { + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + when(artifactCassandraDao.getCountOfArtifactById(any(String.class))).thenReturn(Either.left(new Long(1))); + when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.GENERAL_ERROR); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperation = + interfaceOperationBusinessLogic.updateInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); + Assert.assertTrue(interfaceOperation.isRight()); } @Test - public void shouldFailCreateInterfaceOperationWhenCreateOperationFailedTest() { - Resource resource = createResourceObjectCsar(true); - resource.setInterfaces(new HashMap<>()); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - operation = InterfaceOperationTestUtils.createMockOperation(); - when(interfaceOperation.addInterfaceOperation(any(), any(), any())).thenReturn(Either.left(InterfaceOperationTestUtils.mockOperationToReturn())); - when(interfaceOperation.addInterface(anyString(), any())).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + public void updateInterfaceOperationTestWithoutArtifact() { + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + when(artifactCassandraDao.getCountOfArtifactById(any(String.class))) + .thenReturn(Either.right(CassandraOperationStatus.NOT_FOUND)); + when(interfaceOperation.updateInterfaces(any(), any())).thenReturn(Either.left( + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId)))); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperation = + interfaceOperationBusinessLogic.updateInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); + Assert.assertTrue(interfaceOperation.isLeft()); + } - Either<Operation, ResponseFormat> interfaceOperation = bl.createInterfaceOperation(resourceId, operation, user, true); + @Test + public void updateInterfaceOperationTestDoesntExist() { + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperation = + interfaceOperationBusinessLogic.updateInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); Assert.assertTrue(interfaceOperation.isRight()); - } - @Test() - public void shouldFailWhenCreateInterfaceOperationFailedTest() { - Resource resource = createResourceForInterfaceOperation(); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - operation = InterfaceOperationTestUtils.createMockOperation(); + @Test + public void createInterfaceOperationTestFailOnException() { + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + when(interfaceOperation.updateInterfaces(any(), any())).thenThrow(new RuntimeException()); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperationEither = + interfaceOperationBusinessLogic.createInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); + Assert.assertTrue(interfaceOperationEither.isRight()); + } - when(interfaceOperation.addInterfaceOperation(any(), any(), any())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); - Assert.assertTrue(bl.createInterfaceOperation(resourceId, operation, user, true).isRight()); + @Test + public void createInterfaceOperationTestFailOnFetchinGlobalTypes() { + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperationEither = + interfaceOperationBusinessLogic.createInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); + Assert.assertTrue(interfaceOperationEither.isRight()); } @Test - public void updateInterfaceOperationTest() { - validateUserRoles(Role.ADMIN, Role.DESIGNER); - operation = InterfaceOperationTestUtils.createMockOperation(); - Resource resource = createResourceForInterfaceOperation(); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - when(interfaceOperation.updateInterfaceOperation(any(), any(), any())).thenReturn(Either.left(InterfaceOperationTestUtils.mockOperationToReturn())); + public void createInterfaceOperationTestFailOnValidation() { + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(Collections.emptyMap())); + when(interfaceOperationValidation + .validateInterfaceOperations(anyObject(), anyObject(), any(), anyMap(), anyBoolean())) + .thenReturn(Either.right(new ResponseFormat())); + Either<List<InterfaceDefinition>, ResponseFormat> interfaceOperationEither = + interfaceOperationBusinessLogic.createInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, + operationId)), + user, true); + Assert.assertTrue(interfaceOperationEither.isRight()); + } - Either<Operation, ResponseFormat> interfaceOperation = bl.updateInterfaceOperation(resourceId, operation, user, true); - Assert.assertTrue(interfaceOperation.isLeft()); + @Test + public void deleteInterfaceOperationTestInterfaceDoesntExist() { + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId1, + Collections.singletonList(operationId), user, true).isRight()); } - @Test() - public void shouldFailWhenFailedToUpdateInterfaceOperationTest() { - validateUserRoles(Role.ADMIN, Role.DESIGNER); - operation = InterfaceOperationTestUtils.createMockOperation(); - Resource resource = createResourceForInterfaceOperation(); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - when(interfaceOperation.addInterfaceOperation(any(), any(), any())).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); - Either<Operation, ResponseFormat> interfaceOperation = bl.updateInterfaceOperation(resourceId, operation, user, true); - Assert.assertTrue(interfaceOperation.isRight()); + @Test + public void deleteInterfaceOperationTestOperationDoesntExist() { + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId1), user, true).isRight()); } @Test - public void deleteInterfaceOperationTest() { - Resource resource = createResourceForInterfaceOperation(); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - when(interfaceOperation.deleteInterfaceOperation(any(),any(), any())).thenReturn(Either.left(InterfaceOperationTestUtils.mockOperationToReturn())); + public void deleteInterfaceOperationTestSuccess() { + resource.getInterfaces().get(interfaceId).getOperations() + .putAll(InterfaceOperationTestUtils.createMockOperationMap(operationId1)); when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.OK); - Either<Operation, ResponseFormat> deleteResourceResponseFormatEither = bl.deleteInterfaceOperation(resourceId, operationId, user, true); - Assert.assertTrue(deleteResourceResponseFormatEither.isLeft()); + when(interfaceOperation.updateInterfaces(any(), any())).thenReturn(Either.left(Collections.emptyList())); + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isLeft()); } - @Test() + @Test public void shouldFailWhenDeleteInterfaceOperationFailedTest() { - Resource resource = createResourceForInterfaceOperation(); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - when(interfaceOperation.deleteInterfaceOperation(any(),any(), any())).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.OK); - Assert.assertTrue(bl.deleteInterfaceOperation(resourceId, operationId, user, true).isRight()); + when(interfaceOperation.updateInterfaces(any(), any())) + .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isRight()); + } + @Test + public void deleteInterfaceOperationTestFailOnArtifactDeletion() { + when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.GENERAL_ERROR); + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isRight()); } + @Test - public void getInterfaceOperationTest() { - Resource resource = createResourceForInterfaceOperation(); - resource.setComponentType(ComponentTypeEnum.RESOURCE); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(toscaOperationFacade.getToscaElement(resourceId)).thenReturn(Either.left(resource)); - Either<Operation, ResponseFormat> getResourceResponseFormatEither = bl.getInterfaceOperation(resourceId, operationId, user, true); - Assert.assertTrue(getResourceResponseFormatEither.isLeft()); + public void deleteInterfaceOperationTestFailOnException() { + when(artifactCassandraDao.deleteArtifact(any(String.class))).thenThrow(new RuntimeException()); + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isRight()); } @Test - public void updateToscaResourceNameWhenComponentNameChanged() { - Component newComponent = new Resource(); - newComponent.setName("newComponent"); - Component oldComponent = createResourceForInterfaceOperation(); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(interfaceOperation.updateInterface(anyString(), any())).thenReturn(Either.left(InterfaceOperationTestUtils.mockInterfaceDefinitionToReturn(RESOURCE_NAME))); - Assert.assertTrue(bl.validateComponentNameAndUpdateInterfaces(oldComponent, newComponent).isLeft()); + public void deleteInterfaceTestSuccess() { + when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.OK); + when(interfaceOperation.updateInterfaces(any(), any())).thenReturn(Either.left(Collections.emptyList())); + when(interfaceOperation.deleteInterface(any(), any())).thenReturn(Either.left(interfaceId)); + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isLeft()); } @Test - public void shouldFailWhenComponentNameChangedButUpdateOperationFailed() { - Component newComponent = new Resource(); - newComponent.setName("newComponent"); - Component oldComponent = createResourceForInterfaceOperation(); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(interfaceOperation.updateInterface(anyString(), anyObject())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); - - Assert.assertTrue(bl.validateComponentNameAndUpdateInterfaces(oldComponent, newComponent).isRight()); + public void deleteInterfaceTestFailure() { + when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.OK); + when(interfaceOperation.updateInterfaces(any(), any())).thenReturn(Either.left(Collections.emptyList())); + when(interfaceOperation.deleteInterface(any(), any())) + .thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isRight()); } - @Test(expected = Exception.class) - public void shouldThrowExceptionWhenComponentNameChangedButUpdateOperationFailed() { - Component newComponent = new Resource(); - newComponent.setName("newComponent"); - Component oldComponent = createResourceForInterfaceOperation(); - validateUserRoles(Role.ADMIN, Role.DESIGNER); - when(interfaceOperation.updateInterface(anyString(), anyObject())).thenThrow(new Exception()); - bl.validateComponentNameAndUpdateInterfaces(oldComponent, newComponent).isRight(); + @Test + public void getInterfaceOperationTestInterfaceDoesntExist() { + Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId1, + Collections.singletonList(operationId), user, true).isRight()); } - private void validateUserRoles(Role... roles) { - List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList()); + @Test + public void getInterfaceOperationTestOperationDoesntExist() { + Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId1), user, true).isRight()); } - private void setCanWorkOnResource(Resource resource) { - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - resource.setLastUpdaterUserId(user.getUserId()); + @Test + public void getInterfaceOperationTest() { + Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isLeft()); } - private Resource createResourceForInterfaceOperation() { - Resource resource = new Resource(); - resource.setUniqueId(resourceId); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("Resource name for response"); - resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinition(RESOURCE_NAME)); - return resource; + @Test + public void getInterfaceOperationTestFailOnException() { + when(titanDao.commit()).thenThrow(new RuntimeException()); + Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isRight()); } - private Resource createResourceObjectCsar(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<>(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List<String> template = new ArrayList<>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setResourceVendorModelNumber(""); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - resource.setCsarUUID("valid_vf.csar"); - resource.setCsarVersion("1"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; + @Test + public void shouldFailWhenLockComponentFailedTest() { + when(graphLockOperation.lockComponent(Mockito.anyString(), eq(NodeTypeEnum.Resource))) + .thenReturn(StorageOperationStatus.NOT_FOUND); + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isRight()); + Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isRight()); + Assert.assertTrue(interfaceOperationBusinessLogic.createInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId)), + user, true).isRight()); } - private Resource createResourceObject(boolean afterCreate) { - Resource resource = new Resource(); - resource.setName(RESOURCE_NAME); - resource.addCategory(RESOURCE_CATEGORY1, RESOURCE_SUBCATEGORY); - resource.setDescription("My short description"); - List<String> tgs = new ArrayList<>(); - tgs.add("test"); - tgs.add(resource.getName()); - resource.setTags(tgs); - List<String> template = new ArrayList<>(); - template.add("Root"); - resource.setDerivedFrom(template); - resource.setVendorName("Motorola"); - resource.setVendorRelease("1.0.0"); - resource.setContactId("ya5467"); - resource.setIcon("MyIcon"); - - if (afterCreate) { - resource.setName(resource.getName()); - resource.setVersion("0.1"); - resource.setUniqueId(resource.getName().toLowerCase() + ":" + resource.getVersion()); - resource.setCreatorUserId(user.getUserId()); - resource.setCreatorFullName(user.getFirstName() + " " + user.getLastName()); - resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); - } - return resource; + @Test + public void shouldFailWhenGetComponentFailedTest() { + when(toscaOperationFacade.getToscaElement(resourceId)) + .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isRight()); + Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId, + Collections.singletonList(operationId), user, true).isRight()); + Assert.assertTrue(interfaceOperationBusinessLogic.createInterfaceOperation(resourceId, + Collections.singletonList(InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId)), + user, true).isRight()); } @Test public void testGetAllInterfaceLifecycleTypes_TypesNotFound() { - when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); - Either<Map<String, InterfaceDefinition>, ResponseFormat> response = bl.getAllInterfaceLifecycleTypes(); + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + Either<Map<String, InterfaceDefinition>, ResponseFormat> response = + interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(); Assert.assertTrue(response.isRight()); } @Test public void testGetAllInterfaceLifecycleTypes_Success() { - final String UNIQUE_ID = "UNIQUE_ID"; - final String TYPE = "UNIQUE_ID"; InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); - interfaceDefinition.setUniqueId(UNIQUE_ID); - interfaceDefinition.setType(TYPE); + interfaceDefinition.setUniqueId(interfaceId); + interfaceDefinition.setType(interfaceId); Map<String, InterfaceDefinition> interfaceDefinitionMap = new HashMap<>(); interfaceDefinitionMap.put(interfaceDefinition.getUniqueId(), interfaceDefinition); - when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()).thenReturn(Either.left(interfaceDefinitionMap)); - Either<Map<String, InterfaceDefinition>, ResponseFormat> response = bl.getAllInterfaceLifecycleTypes(); - Assert.assertEquals(response.left().value().size(),1); + when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()) + .thenReturn(Either.left(interfaceDefinitionMap)); + Either<Map<String, InterfaceDefinition>, ResponseFormat> response = + interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(); + Assert.assertEquals(1, response.left().value().size()); } }
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java index b6a7c98efa..8e35981722 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/ResourceBusinessLogicTest.java @@ -32,7 +32,6 @@ import org.openecomp.sdc.ElementOperationMock; import org.openecomp.sdc.be.auditing.impl.AuditingManager; import org.openecomp.sdc.be.datamodel.api.HighestFilterEnum; import org.openecomp.sdc.be.model.operations.StorageException; -import org.openecomp.sdc.test.utils.InterfaceOperationTestUtils; import org.openecomp.sdc.be.components.csar.CsarBusinessLogic; import org.openecomp.sdc.be.components.csar.CsarInfo; import org.openecomp.sdc.be.components.impl.ArtifactsBusinessLogic.ArtifactOperationEnum; @@ -60,7 +59,6 @@ import org.openecomp.sdc.be.model.PropertyDefinition; import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.be.model.cache.ApplicationDataTypeCache; -import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation; import org.openecomp.sdc.be.model.jsontitan.operations.NodeTypeOperation; import org.openecomp.sdc.be.model.jsontitan.operations.TopologyTemplateOperation; @@ -156,8 +154,6 @@ public class ResourceBusinessLogicTest { UserValidations userValidations = Mockito.mock(UserValidations.class); WebApplicationContext webAppContext = Mockito.mock(WebApplicationContext.class); IInterfaceLifecycleOperation interfaceTypeOperation = Mockito.mock(IInterfaceLifecycleOperation.class); - InterfaceOperation interfaceOperation = Mockito.mock(InterfaceOperation.class); - InterfaceOperationBusinessLogic interfaceOperationBl = Mockito.mock(InterfaceOperationBusinessLogic.class); @InjectMocks ResourceBusinessLogic bl = new ResourceBusinessLogic(); @@ -228,7 +224,6 @@ public class ResourceBusinessLogicTest { /*when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.VF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.PNF, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount); when(toscaOperationFacade.validateComponentNameExists(RESOURCE_NAME, ResourceTypeEnum.CR, ComponentTypeEnum.RESOURCE)).thenReturn(eitherCount);*/ - when(interfaceOperation.updateInterface(anyString(), anyObject())).thenReturn(Either.left(InterfaceOperationTestUtils.mockInterfaceDefinitionToReturn(RESOURCE_NAME))); Either<Boolean, StorageOperationStatus> validateDerivedExists = Either.left(true); when(toscaOperationFacade.validateToscaResourceNameExists("Root")).thenReturn(validateDerivedExists); @@ -245,7 +240,6 @@ public class ResourceBusinessLogicTest { Map<String, DataTypeDefinition> emptyDataTypes = new HashMap<>(); when(applicationDataTypeCache.getAll()).thenReturn(Either.left(emptyDataTypes)); when(mockTitanDao.commit()).thenReturn(TitanOperationStatus.OK); - when(interfaceOperationBl.validateComponentNameAndUpdateInterfaces(any(Component.class), any(Component.class))).thenReturn(Either.left(true)); // BL object artifactManager.setNodeTemplateOperation(nodeTemplateOperation); @@ -267,8 +261,6 @@ public class ResourceBusinessLogicTest { bl.setToscaOperationFacade(toscaOperationFacade); bl.setUserValidations(userValidations); bl.setInterfaceTypeOperation(interfaceTypeOperation); - bl.setInterfaceOperation(interfaceOperation); - bl.setInterfaceOperationBusinessLogic(interfaceOperationBl); csarBusinessLogic.setCsarOperation(csarOperation); Resource resourceCsar = createResourceObjectCsar(true); @@ -950,7 +942,6 @@ public class ResourceBusinessLogicTest { @Test public void testResourceNameWrongFormat_UPDATE() { Resource resource = createResourceObject(true); - resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinition(RESOURCE_NAME)); Resource updatedResource = createResourceObject(true); // this is in order to prevent failing with 403 earlier @@ -972,7 +963,6 @@ public class ResourceBusinessLogicTest { @Test public void testResourceNameAfterCertify_UPDATE() { Resource resource = createResourceObject(true); - resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinition(RESOURCE_NAME)); Resource updatedResource = createResourceObject(true); // this is in order to prevent failing with 403 earlier @@ -996,7 +986,6 @@ public class ResourceBusinessLogicTest { @Test public void testResourceNameAlreadyExist_UPDATE() { Resource resource = createResourceObject(true); - resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinition(RESOURCE_NAME)); Resource updatedResource = createResourceObject(true); // this is in order to prevent failing with 403 earlier diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtilsTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtilsTest.java new file mode 100644 index 0000000000..59f95ba8da --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtilsTest.java @@ -0,0 +1,95 @@ +package org.openecomp.sdc.be.components.utils; + +import java.util.Map; +import java.util.Optional; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.Operation; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.test.utils.InterfaceOperationTestUtils; + +public class InterfaceOperationUtilsTest { + + private static final String TEST_RESOURCE_NAME = "TestResource"; + private static final String operationId = "operationId"; + private static final String interfaceId = "interfaceId"; + private static Resource resource; + + @Before + public void setup() { + resource = + new ResourceBuilder().setComponentType(ComponentTypeEnum.RESOURCE).setName(TEST_RESOURCE_NAME).build(); + resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceId, operationId)); + } + + @Test + public void testGetInterfaceDefinitionFromComponentByInterfaceTypeSuccess() { + Assert.assertTrue( + InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(resource, interfaceId) + .isPresent()); + } + + @Test + public void testGetInterfaceDefinitionFromComponentByInterfaceTypeFailure() { + Assert.assertFalse( + InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(resource, TEST_RESOURCE_NAME) + .isPresent()); + } + + @Test + public void testGetInterfaceDefinitionFromComponentByInterfaceTypeNoInterface() { + resource.getInterfaces().clear(); + Assert.assertFalse( + InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(resource, interfaceId) + .isPresent()); + } + + @Test + public void testGetInterfaceDefinitionFromComponentByInterfaceIdSuccess() { + Assert.assertTrue( + InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId(resource, interfaceId) + .isPresent()); + } + + @Test + public void testGetInterfaceDefinitionFromComponentByInterfaceIdFailure() { + Assert.assertFalse( + InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId(resource, TEST_RESOURCE_NAME) + .isPresent()); + } + + @Test + public void testGetInterfaceDefinitionFromComponentByInterfaceIdNoInterface() { + resource.getInterfaces().clear(); + Assert.assertFalse( + InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceId(resource, interfaceId) + .isPresent()); + } + + @Test + public void testGetOperationFromInterfaceDefinitionSuccess() { + Assert.assertTrue(InterfaceOperationUtils.getOperationFromInterfaceDefinition( + InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId), operationId).isPresent()); + } + + @Test + public void testGetOperationFromInterfaceDefinitionFailure() { + Assert.assertFalse(InterfaceOperationUtils.getOperationFromInterfaceDefinition( + InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId), TEST_RESOURCE_NAME) + .isPresent()); + } + + @Test + public void testGetOperationFromInterfaceDefinitionNoOperationMap() { + InterfaceDefinition interfaceDefinition = + InterfaceOperationTestUtils.createMockInterface(interfaceId, operationId); + interfaceDefinition.getOperations().clear(); + Optional<Map.Entry<String, Operation>> operationEntry = + InterfaceOperationUtils.getOperationFromInterfaceDefinition(interfaceDefinition, TEST_RESOURCE_NAME); + Assert.assertFalse(operationEntry.isPresent()); + } + +}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidationTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidationTest.java index 1a112c583b..fc1b03ed78 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidationTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/components/validation/InterfaceOperationValidationTest.java @@ -19,264 +19,344 @@ package org.openecomp.sdc.be.components.validation; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -import com.google.common.collect.Sets; -import fj.data.Either; - -import java.util.ArrayList; -import java.util.Collection; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.be.components.impl.ResponseFormatManager; +import org.openecomp.sdc.be.components.utils.ResourceBuilder; 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.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; -import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.Component; import org.openecomp.sdc.be.model.InputDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.Component; -import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.exception.ResponseFormat; import org.openecomp.sdc.test.utils.InterfaceOperationTestUtils; public class InterfaceOperationValidationTest { - private final Component component = setUpComponentMock(); + private static final String resourceId = "resourceId"; + private static final String interfaceId = "interfaceId"; + private static final String operationId = "operationId"; + private static final String interfaceType = "interfaceType"; + private static final String operationType = "operationType"; + private static final String operationId2 = "operationId2"; + private static final String inputId = "inputId"; + private static final String outputId = "outputId"; + private final InterfaceOperationValidationUtilTest interfaceOperationValidationUtilTest = + new InterfaceOperationValidationUtilTest(); + private final ListDataDefinition<OperationInputDefinition> operationInputDefinitionList = + new ListDataDefinition<>(); + private final ListDataDefinition<OperationOutputDefinition> operationOutputDefinitionList = + new ListDataDefinition<>(); + private Component component; private ResponseFormatManager responseFormatManagerMock; - private final InterfaceOperationValidationUtilTest interfaceOperationValidationUtilTest = new InterfaceOperationValidationUtilTest(); - private final ListDataDefinition<OperationInputDefinition> operationInputDefinitionList = new ListDataDefinition<>(); - private final ListDataDefinition<OperationOutputDefinition> operationOutputDefinitionList = new ListDataDefinition<>(); - @Before - public void init() { + public void setup() { MockitoAnnotations.initMocks(this); responseFormatManagerMock = Mockito.mock(ResponseFormatManager.class); when(responseFormatManagerMock.getResponseFormat(any())).thenReturn(new ResponseFormat()); when(responseFormatManagerMock.getResponseFormat(any(), any())).thenReturn(new ResponseFormat()); when(responseFormatManagerMock.getResponseFormat(any(), any(), any())).thenReturn(new ResponseFormat()); + + component = new ResourceBuilder().setComponentType(ComponentTypeEnum.RESOURCE).setUniqueId(resourceId) + .setName(resourceId).build(); + component.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceId, operationId)); + component.setInputs(createInputsForComponent()); } - @Test - public void shouldPassOperationValidationForHappyScenario() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList,"upgrade"); - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isLeft()); + private List<InputDefinition> createInputsForComponent() { + InputDefinition inputDefinition1 = new InputDefinition(); + inputDefinition1.setName(inputId); + inputDefinition1.setInputId(inputId); + inputDefinition1.setUniqueId(inputId); + inputDefinition1.setValue(inputId); + inputDefinition1.setDefaultValue(inputId); + + InputDefinition inputDefinition2 = new InputDefinition(); + inputDefinition2.setName(outputId); + inputDefinition2.setInputId(outputId); + inputDefinition2.setUniqueId(outputId); + inputDefinition2.setValue(outputId); + inputDefinition2.setDefaultValue(outputId); + + return Arrays.asList(inputDefinition1, inputDefinition2); } @Test - public void shouldFailWhenOperationOperationDescriptionLengthInvalid() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2 - The Spring Initializer provides a project generator to make you " + - "productive with the certain technology stack from the beginning. You can create a skeleton project" + - "with web, data access (relational and NoSQL data stores), cloud, or messaging support", - new ArtifactDefinition(), operationInputDefinitionList, operationOutputDefinitionList,"update"); - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isRight()); + public void shouldPassOperationValidationForHappyScenario() { + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "upgrade"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isLeft()); } - + private InterfaceDefinition createInterfaceOperationData(String uniqueId, String description, + ArtifactDefinition artifactDefinition, ListDataDefinition<OperationInputDefinition> inputs, + ListDataDefinition<OperationOutputDefinition> outputs, String name) { + Operation operation = new Operation(); + operation.setUniqueId(uniqueId); + operation.setDescription(description); + operation.setImplementation(artifactDefinition); + operation.setInputs(inputs); + operation.setOutputs(outputs); + operation.setName(name); + Map<String, Operation> operationMap = new HashMap<>(); + operationMap.put(operation.getUniqueId(), operation); + InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); + interfaceDefinition.setOperationsMap(operationMap); + return interfaceDefinition; + } @Test public void shouldFailWhenOperationNameIsEmpty() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList, ""); - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isRight()); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, ""); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isRight()); } @Test - public void shouldFailWhenOperationNamesAreNotUnique() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList,"CREATE"); - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isRight()); + public void shouldFailWhenOperationNamesAreNotUniqueForCreate() { + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, operationId); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isRight()); } @Test - public void shouldFailWhenOperationNameLengthIsInvalid() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList, - "interface operation2 - The Spring Initializer provides a project generator to make you " + - "productive with the certain technology stack from the beginning. You can create a skeleton project" + - "with web, data access (relational and NoSQL data stores), cloud, or messaging support"); - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isRight()); + public void shouldNotFailWhenOperationNamesAreNotUniqueForUpdate() { + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, operationId); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), true) + .isLeft()); } + @Test + public void shouldFailWhenOperationNameLengthIsInvalid() { + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, + "interface operation2 - The Spring Initializer provides a project generator to make you " + + "productive with the certain technology stack from the beginning. " + + "You can create a skeleton project" + + "with web, data access (relational and NoSQL data stores), " + + "cloud, or messaging support"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces() + .get(interfaceId), Collections.emptyMap(), false) + .isRight()); + } @Test public void shouldFailWhenOperationInputParamNamesAreNotUnique() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label2")); - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label2")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList,"create"); - - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isRight()); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(outputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "create"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isRight()); } @Test public void shouldPassWhenOperationInputParamNamesAreUnique() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label2")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList,"update"); - - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isLeft()); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(outputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "update"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isLeft()); } @Test public void shouldPassWhenOperationInputParamNamesHasSubProperty() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label2")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList,"update"); - operationInputDefinitionList.getListToscaDataDefinition().get(0).setInputId(operationInputDefinitionList - .getListToscaDataDefinition().get(0).getInputId().concat(".subproperty")); - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isLeft()); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "update"); + operationInputDefinitionList.getListToscaDataDefinition().get(0).setInputId( + operationInputDefinitionList.getListToscaDataDefinition().get(0).getInputId().concat(".subproperty")); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isLeft()); } @Test public void shouldFailWhenOperationInputParamNameEmpty() { operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(" ")); - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList,"update"); - - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isRight()); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "update"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isRight()); } @Test public void shouldFailWhenOperationOutputParamNameEmpty() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("inputParam")); - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(" ")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList,"update"); - - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isRight()); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "update"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isRight()); } @Test public void shouldPassWhenInterfaceOperationOutputParamNamesUnique() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("label2")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList,"update"); - - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isLeft()); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "update"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isLeft()); } @Test public void shouldFailWhenOperationOutputParamNamesAreNotUnique() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("inputParam1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("outParam1")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("outParam2")); - operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition("outParam2")); - Collection<Operation> operations = createInterfaceOperationData("op2", - "interface operation2",new ArtifactDefinition(), operationInputDefinitionList, - operationOutputDefinitionList,"update"); - - Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest - .validateInterfaceOperations(operations, component, false); - Assert.assertTrue(booleanResponseFormatEither.isRight()); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "update"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isRight()); } - private Set<Operation> createInterfaceOperationData( String uniqueID, String description, ArtifactDefinition artifactDefinition, - ListDataDefinition<OperationInputDefinition> inputs, - ListDataDefinition<OperationOutputDefinition> outputs, String name) { - return Sets.newHashSet(InterfaceOperationTestUtils.createInterfaceOperation(uniqueID, description, artifactDefinition, inputs, outputs, name)); + @Test + public void shouldPassWhenOperationInputParamExistInComponentProperty() { + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "update"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isLeft()); } - private Component setUpComponentMock(){ - Component component = new Resource(); - - List<InputDefinition> inputs = new ArrayList<>(); - InputDefinition inputDefinition = new InputDefinition(); - InputDefinition inputDefinition1 = new InputDefinition(); - - List<ComponentInstanceInput> componentInstanceInputs = new ArrayList<>(); - ComponentInstanceInput componentInstanceInput1 = new ComponentInstanceInput(); - componentInstanceInput1.setComponentInstanceName("componentInstance1"); - componentInstanceInput1.setUniqueId("inputId1"); - ComponentInstanceInput componentInstanceInput2 = new ComponentInstanceInput(); - componentInstanceInput2.setComponentInstanceName("componentInstance2"); - componentInstanceInput2.setUniqueId("inputId2"); - - componentInstanceInputs.add(componentInstanceInput1); - componentInstanceInputs.add(componentInstanceInput2); + @Test + public void shouldFailWhenOperationInputParamDoesntExistInComponentProperty() { + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(operationId)); + operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(outputId)); + InterfaceDefinition interfaceDefinition = + createInterfaceOperationData(operationId2, operationId2, new ArtifactDefinition(), + operationInputDefinitionList, operationOutputDefinitionList, "update"); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(interfaceDefinition, component, + component.getInterfaces().get(interfaceId), Collections.emptyMap(), false) + .isRight()); + } - inputDefinition.setUniqueId("inputId1"); - inputDefinition.setInputs(componentInstanceInputs); - inputDefinition1.setUniqueId("uniqueId3"); + @Test + public void shouldFailValidateAllowedOperationCountOnLocalInterfaceType() { + InterfaceDefinition inputInterfaceDefinition = + InterfaceOperationTestUtils.createMockInterface(interfaceId, operationType); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(inputInterfaceDefinition, component, + component.getInterfaces().get(interfaceId), + InterfaceOperationTestUtils.createMockInterfaceTypeMap(interfaceType, + operationType), + false).isRight()); + } - inputs.add(inputDefinition); - inputs.add(inputDefinition1); - component.setInputs(inputs); - component.setInterfaces(createMockInterfaceDefinition()); - return component; + @Test + public void shouldFailValidateAllowedOperationsOnGlobalInterfaceType() { + InterfaceDefinition inputInterfaceDefinition = + InterfaceOperationTestUtils.createMockInterface(interfaceType, operationId); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(inputInterfaceDefinition, component, + component.getInterfaces().get(interfaceId), + InterfaceOperationTestUtils.createMockInterfaceTypeMap(interfaceType, + operationType), + false).isRight()); } - private Map<String, InterfaceDefinition> createMockInterfaceDefinition() { - Map<String, Operation> operationMap = InterfaceOperationTestUtils.createMockOperationMap(); - Map<String, InterfaceDefinition> interfaceDefinitionMap = new HashMap<>(); - interfaceDefinitionMap.put("int1", InterfaceOperationTestUtils.createInterface("int1", "Interface 1", - "lifecycle", "tosca", operationMap)); + @Test + public void shouldPassValidateAllowedOperationsOnGlobalInterfaceType() { + InterfaceDefinition inputInterfaceDefinition = + InterfaceOperationTestUtils.createMockInterface(interfaceType, operationType); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(inputInterfaceDefinition, component, + component.getInterfaces().get(interfaceId), + InterfaceOperationTestUtils.createMockInterfaceTypeMap(interfaceType, + operationType), + false).isLeft()); + } - return interfaceDefinitionMap; + @Test + public void shouldFailValidateOperationNameUniquenessInCollection() { + InterfaceDefinition inputInterfaceDefinition = + InterfaceOperationTestUtils.createMockInterface(interfaceType, operationType); + inputInterfaceDefinition.getOperations() + .put(operationId, InterfaceOperationTestUtils.createMockOperation(operationType)); + Assert.assertTrue(interfaceOperationValidationUtilTest + .validateInterfaceOperations(inputInterfaceDefinition, component, + component.getInterfaces().get(interfaceId), + InterfaceOperationTestUtils.createMockInterfaceTypeMap(interfaceType, + operationType), + false).isRight()); } private class InterfaceOperationValidationUtilTest extends InterfaceOperationValidation { diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/utils/InterfaceUIDataConverterTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/utils/InterfaceUIDataConverterTest.java deleted file mode 100644 index 0c02e71bd2..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/utils/InterfaceUIDataConverterTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.openecomp.sdc.be.datamodel.utils; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationDataDefinition; -import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationParamDataDefinition; -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.model.Operation; - -import static org.openecomp.sdc.test.utils.InterfaceOperationTestUtils.createMockOperationInputDefinition; -import static org.openecomp.sdc.test.utils.InterfaceOperationTestUtils.createMockOperationOutputDefinition; - -public class InterfaceUIDataConverterTest { - - @Test - public void testConvertInterfaceDataToOperationData() { - InterfaceOperationDataDefinition interfaceOperation = createIODD("test", - "test description", - createParamDataList("inpName", "property", true, "String"), - createParamDataList("OutName", null, true, "String"), - "workflowId", - "workflowVersionId"); - Operation result; - result = InterfaceUIDataConverter.convertInterfaceDataToOperationData(interfaceOperation); - Assert.assertNotNull(result); - } - - @Test - public void testConvertInterfaceDataToOperationDataWithoutMandatory() { - ListDataDefinition<InterfaceOperationParamDataDefinition> iopd = new ListDataDefinition<>(); - iopd.add(createParamData("test", "property", "String")); - InterfaceOperationDataDefinition interfaceOperation = createIODD("test", - "test description", iopd, iopd, - "workflowId", - "workflowVersionId"); - Operation result; - result = InterfaceUIDataConverter.convertInterfaceDataToOperationData(interfaceOperation); - Assert.assertNotNull(result); - } - - @Test - public void testConvertInterfaceDataToOperationDataWithoutOptionalFields() { - InterfaceOperationDataDefinition interfaceOperation = new InterfaceOperationDataDefinition(); - interfaceOperation.setOperationType("operationType"); - Operation result; - result = InterfaceUIDataConverter.convertInterfaceDataToOperationData(interfaceOperation); - Assert.assertNotNull(result); - } - - @Test - public void testConvertOperationDataToInterfaceData() { - Operation operationData = new Operation(); - InterfaceOperationDataDefinition result; - ListDataDefinition<OperationInputDefinition> inputs = new ListDataDefinition<>(); - inputs.add(createMockOperationInputDefinition("Inp1")); - ListDataDefinition<OperationOutputDefinition> outputs = new ListDataDefinition<>(); - outputs.add(createMockOperationOutputDefinition("out1")); - operationData.setInputs(inputs); - operationData.setOutputs(outputs); - operationData.setImplementation(new ArtifactDataDefinition()); - result = InterfaceUIDataConverter.convertOperationDataToInterfaceData(operationData); - Assert.assertNotNull(result); - } - - private InterfaceOperationDataDefinition createIODD(String operationType, String description, - ListDataDefinition<InterfaceOperationParamDataDefinition> inputParams, - ListDataDefinition<InterfaceOperationParamDataDefinition> outputParams, - String workflowId, - String workflowVersionId) { - InterfaceOperationDataDefinition interfaceOperation = new InterfaceOperationDataDefinition(); - interfaceOperation.setOperationType(operationType); - interfaceOperation.setDescription(description); - interfaceOperation.setInputParams(inputParams); - interfaceOperation.setOutputParams(outputParams); - interfaceOperation.setWorkflowId(workflowId); - interfaceOperation.setWorkflowVersionId(workflowVersionId); - return interfaceOperation; - } - - private InterfaceOperationParamDataDefinition createParamData(String name, String property, boolean mandatory, String type) { - InterfaceOperationParamDataDefinition definition = createParamData(name, property, type); - definition.setMandatory(mandatory); - return definition; - } - - private InterfaceOperationParamDataDefinition createParamData(String name, String property, String type) { - InterfaceOperationParamDataDefinition definition = new InterfaceOperationParamDataDefinition(); - definition.setName(name); - definition.setProperty(property); - definition.setType(type); - return definition; - } - - private ListDataDefinition<InterfaceOperationParamDataDefinition> createParamDataList(String name, - String property, boolean mandatory, String type) { - ListDataDefinition<InterfaceOperationParamDataDefinition> list = new ListDataDefinition<>(); - list.add(createParamData(name, property, mandatory, type)); - return list; - } - -}
\ No newline at end of file diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java index 2fabe43733..592d27ec5d 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/ToscaExportHandlerTest.java @@ -1,6 +1,7 @@ package org.openecomp.sdc.be.tosca; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -46,6 +47,7 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.category.SubCategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; import org.openecomp.sdc.be.tosca.model.SubstitutionMapping; import org.openecomp.sdc.be.tosca.model.ToscaCapability; import org.openecomp.sdc.be.tosca.model.ToscaMetadata; @@ -82,6 +84,9 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { @Mock GroupExportParserImpl groupExportParserImpl; + @Mock + InterfaceLifecycleOperation interfaceLifecycleOperation; + @Before public void setUpMock() throws Exception { MockitoAnnotations.initMocks(this); @@ -160,7 +165,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { ((Resource) component).setInterfaces(new HashMap<>()); Mockito.when(dataTypeCache.getAll()).thenReturn(Either.right(TitanOperationStatus.NOT_FOUND)); - + Mockito.when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()).thenReturn(Either.left(Collections.emptyMap())); // default test when convertInterfaceNodeType is right result = testSubject.exportComponentInterface(component, false); @@ -392,6 +397,7 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { component.setInputs(inputs); Mockito.when(dataTypeCache.getAll()).thenReturn(Either.left(new HashMap<>())); + Mockito.when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()).thenReturn(Either.left(Collections.emptyMap())); Mockito.when(capabiltyRequirementConvertor.convertRequirements(Mockito.any(Map.class), Mockito.any(Resource.class), Mockito.any(ToscaNodeType.class))).thenReturn(Either.left(new ToscaNodeType())); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtilTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtilTest.java index 8f34e0e29b..983ef91a8c 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtilTest.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/tosca/utils/InterfacesOperationsToscaUtilTest.java @@ -19,6 +19,7 @@ package org.openecomp.sdc.be.tosca.utils; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; import java.util.HashMap; import java.util.Map; @@ -63,15 +64,15 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Resource(); component.setNormalizedName("normalizedComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setToscaResourceName("interface.types.test_resource_name"); + addedInterface.setType("interface.types.test_resource_name"); addOperationsToInterface(addedInterface, 5, 3, true); final String interfaceType = "normalizedComponentName-interface"; component.setInterfaces(new HashMap<>()); component.getInterfaces().put(interfaceType, addedInterface); final Map<String, Object> interfaceTypeElement = - InterfacesOperationsToscaUtil.addInterfaceTypeElement(component); + InterfacesOperationsToscaUtil.addInterfaceTypeElement(component, new ArrayList<>()); - ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null); + ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate("test"); template.setInterface_types(interfaceTypeElement); final ToscaRepresentation toscaRepresentation = handler.createToscaRepresentation(template); @@ -85,15 +86,15 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Service(); component.setNormalizedName("normalizedServiceComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setToscaResourceName("interface.types.test_service_name"); + addedInterface.setType("interface.types.test_service_name"); addOperationsToInterface(addedInterface, 5, 3, true); final String interfaceType = "normalizedServiceComponentName-interface"; component.setInterfaces(new HashMap<>()); component.getInterfaces().put(interfaceType, addedInterface); final Map<String, Object> interfaceTypeElement = - InterfacesOperationsToscaUtil.addInterfaceTypeElement(component); + InterfacesOperationsToscaUtil.addInterfaceTypeElement(component, new ArrayList<>()); - ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null); + ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate("testService"); template.setInterface_types(interfaceTypeElement); final ToscaRepresentation toscaRepresentation = handler.createToscaRepresentation(template); @@ -107,7 +108,7 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Resource(); component.setNormalizedName("normalizedComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setToscaResourceName("com.some.resource.or.other.resourceName"); + addedInterface.setType("com.some.resource.or.other.resourceName"); addOperationsToInterface(addedInterface, 3, 2, true); final String interfaceType = "normalizedComponentName-interface"; @@ -116,7 +117,7 @@ public class InterfacesOperationsToscaUtilTest { ToscaNodeType nodeType = new ToscaNodeType(); InterfacesOperationsToscaUtil.addInterfaceDefinitionElement(component, nodeType, false); - ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null); + ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate(NODE_TYPE_NAME); Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); nodeTypes.put(NODE_TYPE_NAME, nodeType); @@ -139,8 +140,7 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Service(); component.setNormalizedName("normalizedServiceComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setToscaResourceName("com.some.service.or.other.serviceName"); - + addedInterface.setType("com.some.service.or.other.serviceName"); addOperationsToInterface(addedInterface, 3, 2, true); final String interfaceType = "normalizedServiceComponentName-interface"; component.setInterfaces(new HashMap<>()); @@ -148,7 +148,7 @@ public class InterfacesOperationsToscaUtilTest { ToscaNodeType nodeType = new ToscaNodeType(); InterfacesOperationsToscaUtil.addInterfaceDefinitionElement(component, nodeType, false); - ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null); + ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate("testService"); Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); nodeTypes.put(NODE_TYPE_NAME, nodeType); @@ -170,8 +170,7 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Resource(); component.setNormalizedName("normalizedComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setToscaResourceName("com.some.resource.or.other.resourceNameNoInputs"); - + addedInterface.setType("com.some.resource.or.other.resourceNameNoInputs"); addOperationsToInterface(addedInterface, 3, 3, false); final String interfaceType = "normalizedComponentName-interface"; component.setInterfaces(new HashMap<>()); @@ -179,7 +178,7 @@ public class InterfacesOperationsToscaUtilTest { ToscaNodeType nodeType = new ToscaNodeType(); InterfacesOperationsToscaUtil.addInterfaceDefinitionElement(component, nodeType, false); - ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null); + ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); ToscaTemplate template = new ToscaTemplate("test"); Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); nodeTypes.put("test", nodeType); diff --git a/catalog-be/src/test/java/org/openecomp/sdc/test/utils/InterfaceOperationTestUtils.java b/catalog-be/src/test/java/org/openecomp/sdc/test/utils/InterfaceOperationTestUtils.java index 10acd69a79..f21d5a9dcf 100644 --- a/catalog-be/src/test/java/org/openecomp/sdc/test/utils/InterfaceOperationTestUtils.java +++ b/catalog-be/src/test/java/org/openecomp/sdc/test/utils/InterfaceOperationTestUtils.java @@ -27,59 +27,47 @@ import org.openecomp.sdc.be.model.Operation; public class InterfaceOperationTestUtils { - public static InterfaceDefinition createInterface(String uniqueID, String description, String type, - String toscaResourceName, Map<String, Operation> op) { + public static Map<String, InterfaceDefinition> createMockInterfaceDefinitionMap(String interfaceId, + String operationId) { + Map<String, InterfaceDefinition> interfaceDefinitionMap = new HashMap<>(); + interfaceDefinitionMap.put(interfaceId, createMockInterface(interfaceId, operationId)); + return interfaceDefinitionMap; + } + + public static InterfaceDefinition createMockInterface(String interfaceId, String operationId) { + return createInterface(interfaceId, interfaceId, interfaceId, interfaceId, createMockOperationMap(operationId)); + } + + private static InterfaceDefinition createInterface(String uniqueId, String description, String type, + String toscaResourceName, Map<String, Operation> op) { InterfaceDefinition id = new InterfaceDefinition(); id.setType(type); id.setDescription(description); - id.setUniqueId(uniqueID); + id.setUniqueId(uniqueId); id.setToscaResourceName(toscaResourceName); id.setOperationsMap(op); return id; } - public static Operation createInterfaceOperation(String uniqueID, String description, ArtifactDefinition artifactDefinition, - ListDataDefinition<OperationInputDefinition> inputs, - ListDataDefinition<OperationOutputDefinition> outputs, String name) { - Operation operation = new Operation(); - operation.setUniqueId(uniqueID); - operation.setDescription(description); - operation.setImplementation(artifactDefinition); - operation.setInputs(inputs); - operation.setOutputs(outputs); - operation.setName(name); - return operation; - } - - public static InterfaceDefinition mockInterfaceDefinitionToReturn(String resourceName) { - Map<String, Operation> operationMap = createMockOperationMap(); - return createInterface("int1", "Interface 1", - "lifecycle", "org.openecomp.interfaces.node.lifecycle." + resourceName, operationMap); - } - - public static Operation mockOperationToReturn() { - return createMockOperation(); - } - - public static Map<String, Operation> createMockOperationMap() { + public static Map<String, Operation> createMockOperationMap(String operationId) { Map<String, Operation> operationMap = new HashMap<>(); - operationMap.put("op1", createMockOperation()); + operationMap.put(operationId, createMockOperation(operationId)); return operationMap; } - public static Operation createMockOperation() { + public static Operation createMockOperation(String operationId) { Operation operation = new Operation(); ListDataDefinition<OperationInputDefinition> operationInputDefinitionList = new ListDataDefinition<>(); - operationInputDefinitionList.add(createMockOperationInputDefinition("label1")); + operationInputDefinitionList.add(createMockOperationInputDefinition("inputId")); operation.setInputs(operationInputDefinitionList); ListDataDefinition<OperationOutputDefinition> operationOutputDefList = new ListDataDefinition<>(); - operationOutputDefList.add(createMockOperationOutputDefinition("op1")); + operationOutputDefList.add(createMockOperationOutputDefinition("outputId")); operation.setOutputs(operationOutputDefList); operation.setDefinition(false); - operation.setName("CREATE"); - operation.setUniqueId("uniqueId1"); + operation.setName(operationId); + operation.setUniqueId(operationId); ArtifactDefinition implementation = new ArtifactDefinition(); implementation.setUniqueId("uniqId"); implementation.setArtifactUUID("artifactId"); @@ -89,28 +77,41 @@ public class InterfaceOperationTestUtils { return operation; } - public static OperationInputDefinition createMockOperationInputDefinition(String name) { + public static OperationInputDefinition createMockOperationInputDefinition(String inputId) { OperationInputDefinition operationInputDefinition = new OperationInputDefinition(); - operationInputDefinition.setName(name); - operationInputDefinition.setUniqueId("uniqueId1"); - operationInputDefinition.setInputId("inputId1"); + operationInputDefinition.setName(inputId); + operationInputDefinition.setUniqueId(inputId); + operationInputDefinition.setInputId(inputId); + operationInputDefinition.setValue(inputId); + operationInputDefinition.setDefaultValue(inputId); return operationInputDefinition; } - public static OperationOutputDefinition createMockOperationOutputDefinition(String name) { + public static OperationOutputDefinition createMockOperationOutputDefinition(String outputId) { OperationOutputDefinition operationOutputDefinition = new OperationOutputDefinition(); - operationOutputDefinition.setName(name); - operationOutputDefinition.setUniqueId("uniqueId1"); - operationOutputDefinition.setInputId("inputId1"); + operationOutputDefinition.setName(outputId); + operationOutputDefinition.setUniqueId(outputId); + operationOutputDefinition.setInputId(outputId); + operationOutputDefinition.setValue(outputId); + operationOutputDefinition.setDefaultValue(outputId); return operationOutputDefinition; } - public static Map<String, InterfaceDefinition> createMockInterfaceDefinition(String resourceName) { - Map<String, Operation> operationMap = createMockOperationMap(); + public static Map<String, InterfaceDefinition> createMockInterfaceTypeMap(String interfaceType, + String operationType) { + Map<String, Operation> operationMap = createMockOperationTypeMap(operationType); Map<String, InterfaceDefinition> interfaceDefinitionMap = new HashMap<>(); - interfaceDefinitionMap.put("int1", createInterface("int1", "Interface 1", - "lifecycle", "org.openecomp.interfaces.node.lifecycle." + resourceName, operationMap)); + interfaceDefinitionMap.put(interfaceType, + createInterface(interfaceType, interfaceType, interfaceType, interfaceType, operationMap)); return interfaceDefinitionMap; } + private static Map<String, Operation> createMockOperationTypeMap(String operationType) { + Operation operation = new Operation(); + operation.setUniqueId(operationType); + Map<String, Operation> operationMap = new HashMap<>(); + operationMap.put(operationType, operation); + return operationMap; + } + } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java index fa96c45472..82041b4180 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/api/ActionStatus.java @@ -117,13 +117,17 @@ public enum ActionStatus { NO_INSTANCES_TO_UPGRADE, ARCHIVED_ORIGINS_FOUND, + //Interface + INTERFACE_NOT_FOUND_IN_COMPONENT, + //InterfaceOperation - INTERFACE_OPERATION_NOT_FOUND, INTERFACE_OPERATION_NAME_ALREADY_IN_USE, INTERFACE_OPERATION_NAME_MANDATORY, INTERFACE_OPERATION_NAME_INVALID, - INTERFACE_OPERATION_DESCRIPTION_MAX_LENGTH, INTERFACE_OPERATION_INPUT_NAME_ALREADY_IN_USE, INTERFACE_OPERATION_OUTPUT_NAME_ALREADY_IN_USE,INTERFACE_OPERATION_NOT_DELETED, + INTERFACE_OPERATION_NOT_FOUND, INTERFACE_OPERATION_NAME_ALREADY_IN_USE, INTERFACE_OPERATION_NAME_MANDATORY, + INTERFACE_OPERATION_NAME_INVALID, INTERFACE_OPERATION_INPUT_NAME_ALREADY_IN_USE, + INTERFACE_OPERATION_OUTPUT_NAME_ALREADY_IN_USE, INTERFACE_OPERATION_NOT_DELETED, INTERFACE_OPERATION_INPUT_NAME_MANDATORY, INTERFACE_OPERATION_OUTPUT_NAME_MANDATORY, - INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT, + INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT, INTERFACE_OPERATION_INVALID_FOR_LOCAL_TYPE, + INTERFACE_OPERATION_INVALID_FOR_GLOBAL_TYPE, //InterfaceLifeCycleType - INTERFACE_LIFECYCLE_TYPES_NOT_FOUND - ; + INTERFACE_LIFECYCLE_TYPES_NOT_FOUND; } diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java index f9f2ce9b35..b4433d1be0 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperation.java @@ -17,223 +17,82 @@ package org.openecomp.sdc.be.model.jsontitan.operations; import fj.data.Either; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.UUID; -import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao; -import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus; -import org.openecomp.sdc.be.dao.jsongraph.GraphVertex; +import java.util.stream.Collectors; +import org.apache.commons.collections.MapUtils; import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum; -import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum; import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum; import org.openecomp.sdc.be.dao.titan.TitanOperationStatus; +import org.openecomp.sdc.be.datatypes.elements.InterfaceDataDefinition; import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; -import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.Operation; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter; -import org.springframework.beans.factory.annotation.Autowired; @org.springframework.stereotype.Component("interfaces-operation") public class InterfaceOperation extends BaseOperation { - @Autowired - private ArtifactCassandraDao artifactCassandraDao; - - public Either<InterfaceDefinition, StorageOperationStatus> addInterface(String componentId, - InterfaceDefinition interfaceDefinition) { - return addOrUpdateInterface(false, componentId, interfaceDefinition); - } - - public Either<InterfaceDefinition, StorageOperationStatus> updateInterface(String componentId, - InterfaceDefinition interfaceDefinition) { - return addOrUpdateInterface(true, componentId, interfaceDefinition); - } - - private Either<InterfaceDefinition, StorageOperationStatus> addOrUpdateInterface( - boolean isUpdateAction, String componentId, InterfaceDefinition interfaceDefinition) { - - StorageOperationStatus statusRes; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - - getToscaElementRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return Either.right(statusRes); - } - GraphVertex componentVertex = getToscaElementRes.left().value(); - if (!isUpdateAction) { - interfaceDefinition.setUniqueId(UUID.randomUUID().toString()); + public Either<List<InterfaceDefinition>, StorageOperationStatus> addInterfaces(String componentId, + List<InterfaceDefinition> interfaceDefinitions) { + return addOrUpdateInterfaces(false, componentId, interfaceDefinitions); } - statusRes = performUpdateToscaAction(isUpdateAction, componentVertex, - Collections.singletonList(interfaceDefinition), EdgeLabelEnum.INTERFACE, VertexTypeEnum.INTERFACE); - if (!statusRes.equals(StorageOperationStatus.OK)) { - return Either.right(statusRes); - } - return Either.left(interfaceDefinition); - } - - public Either<Operation, StorageOperationStatus> addInterfaceOperation(String componentId, InterfaceDefinition interfaceDef, Operation interfaceOperation) { - return addOrUpdateInterfaceOperation(false, componentId, interfaceDef, interfaceOperation); - } - public Either<Operation, StorageOperationStatus> updateInterfaceOperation(String componentId, InterfaceDefinition interfaceDef, Operation interfaceOperation) { - return addOrUpdateInterfaceOperation(true, componentId, interfaceDef, interfaceOperation); - } + private Either<List<InterfaceDefinition>, StorageOperationStatus> addOrUpdateInterfaces(boolean isUpdateAction, + String componentId, List<InterfaceDefinition> interfaceDefinitions) { - private Either<Operation, StorageOperationStatus> addOrUpdateInterfaceOperation(boolean isUpdateAction, String componentId, InterfaceDefinition interfaceDef, Operation operation) { - - StorageOperationStatus statusRes; - Either<GraphVertex, TitanOperationStatus> getToscaElementRes; - Either<GraphVertex, TitanOperationStatus> getToscaElementInt; - - if(isUpdateAction && operation.getImplementationArtifact() != null){ - String artifactUUID = operation.getImplementationArtifact().getArtifactUUID(); - Either<Long, CassandraOperationStatus> artifactCount = artifactCassandraDao.getCountOfArtifactById(artifactUUID); - if(artifactCount.isLeft()){ - CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUUID); - if (cassandraStatus != CassandraOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraStatus)); + List<ToscaDataDefinition> interfaceDataDefinitions = + interfaceDefinitions.stream().map(InterfaceDataDefinition::new).collect(Collectors.toList()); + StorageOperationStatus statusRes = + performUpdateToscaAction(isUpdateAction, componentId, interfaceDataDefinitions, EdgeLabelEnum.INTERFACE, + VertexTypeEnum.INTERFACE); + if (!statusRes.equals(StorageOperationStatus.OK)) { + return Either.right(statusRes); } - } - } - - getToscaElementRes = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getToscaElementRes.isRight()) { - TitanOperationStatus status = getToscaElementRes.right().value(); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return Either.right(statusRes); - } - GraphVertex componentVertex = getToscaElementRes.left().value(); - getToscaElementInt = titanDao.getChildVertex(componentVertex, EdgeLabelEnum.INTERFACE, JsonParseFlagEnum.NoParse); - if (getToscaElementInt.isRight()) { - TitanOperationStatus status = getToscaElementInt.right().value(); - statusRes = DaoStatusConverter.convertTitanStatusToStorageStatus(status); - return Either.right(statusRes); - } - GraphVertex interfaceVertex = getToscaElementInt.left().value(); - - statusRes = performUpdateToscaAction(isUpdateAction, interfaceVertex, - Collections.singletonList(operation), EdgeLabelEnum.INTERFACE_OPERATION, VertexTypeEnum.INTERFACE_OPERATION); - if (!statusRes.equals(StorageOperationStatus.OK)) { - return Either.right(statusRes); + return Either.left(interfaceDefinitions); } - getUpdatedInterfaceDef(interfaceDef, operation, operation.getUniqueId()); - Either<InterfaceDefinition, StorageOperationStatus> intUpdateStatus = updateInterface(componentId, interfaceDef); - if (intUpdateStatus.isRight() && !intUpdateStatus.right().value().equals(StorageOperationStatus.OK)) { - return Either.right(statusRes); - } - - return Either.left(operation); - } - - public Either<Operation, StorageOperationStatus> deleteInterfaceOperation(String componentId, InterfaceDefinition interfaceDef, String operationToDelete) { - Either<GraphVertex, TitanOperationStatus> getInterfaceVertex; - Either<GraphVertex, TitanOperationStatus> getComponentVertex; - Operation operation = new Operation(); - StorageOperationStatus status; - - getComponentVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.NoParse); - if (getComponentVertex.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getComponentVertex.right().value())); + private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, String componentId, + List<ToscaDataDefinition> toscaDataList, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { + if (isUpdate) { + return updateToscaDataOfToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList, + JsonPresentationFields.UNIQUE_ID); + } else { + return addToscaDataToToscaElement(componentId, edgeLabel, vertexLabel, toscaDataList, + JsonPresentationFields.UNIQUE_ID); + } } - getInterfaceVertex = titanDao.getChildVertex(getComponentVertex.left().value(), EdgeLabelEnum.INTERFACE, JsonParseFlagEnum.NoParse); - if (getInterfaceVertex.isRight()) { - return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(getInterfaceVertex.right().value())); + public Either<List<InterfaceDefinition>, StorageOperationStatus> updateInterfaces(String componentId, + List<InterfaceDefinition> interfaceDefinitions) { + return addOrUpdateInterfaces(true, componentId, interfaceDefinitions); } - if (!interfaceDef.getOperationsMap().isEmpty()) { - Either<GraphVertex, TitanOperationStatus> getInterfaceOpVertex = - titanDao.getChildVertex(getInterfaceVertex.left().value(), EdgeLabelEnum.INTERFACE_OPERATION, - JsonParseFlagEnum.NoParse); - if (getInterfaceOpVertex.isRight()) { - List<ToscaDataDefinition> toscaDataList = new ArrayList<>(interfaceDef.getOperationsMap().values()); - StorageOperationStatus statusRes = - addToscaDataToToscaElement(getInterfaceVertex.left().value(), EdgeLabelEnum.INTERFACE_OPERATION, - VertexTypeEnum.INTERFACE_OPERATION, toscaDataList, JsonPresentationFields.UNIQUE_ID); - if (!statusRes.equals(StorageOperationStatus.OK)) { - return Either.right(statusRes); - } - } - } + public Either<String, StorageOperationStatus> deleteInterface(String componentId, String interfacesToDelete) { - Optional<Entry<String, Operation>> operationToRemove = interfaceDef.getOperationsMap().entrySet().stream() - .filter(entry -> entry.getValue().getUniqueId().equals(operationToDelete)).findAny(); - if (operationToRemove.isPresent()){ - Map.Entry<String, Operation> stringOperationEntry = operationToRemove.get(); - operation = stringOperationEntry.getValue(); - ArtifactDefinition implementationArtifact = operation.getImplementationArtifact(); - if(implementationArtifact != null){ - String artifactUUID = implementationArtifact.getArtifactUUID(); - CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(artifactUUID); - if (cassandraStatus != CassandraOperationStatus.OK) { - return Either.right(DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraStatus)); + StorageOperationStatus statusRes = deleteToscaDataElements(componentId, EdgeLabelEnum.INTERFACE, + Collections.singletonList(interfacesToDelete)); + if (!statusRes.equals(StorageOperationStatus.OK)) { + return Either.right(statusRes); } - } - if(interfaceDef.getOperationsMap().size() > 1){ - status = deleteToscaDataElements(getInterfaceVertex.left().value(), EdgeLabelEnum.INTERFACE_OPERATION, Collections.singletonList(operationToDelete)); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - } else { - status = removeToscaDataVertex(getInterfaceVertex.left().value(), EdgeLabelEnum.INTERFACE_OPERATION, VertexTypeEnum.INTERFACE_OPERATION); - if (status != StorageOperationStatus.OK) { - return Either.right(status); + Either<Map<String, InterfaceDataDefinition>, TitanOperationStatus> componentEither = + getDataFromGraph(componentId, EdgeLabelEnum.INTERFACE); + if (componentEither.isRight()) { + return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(componentEither.right().value())); } - } - getUpdatedInterfaceDef(interfaceDef, null, operationToDelete); - if (interfaceDef.getOperations().isEmpty()) { - status = deleteToscaDataElements(getComponentVertex.left().value(), EdgeLabelEnum.INTERFACE, Collections.singletonList(interfaceDef.getUniqueId())); - if (status != StorageOperationStatus.OK) { - return Either.right(status); - } - status = removeToscaDataVertex(getComponentVertex.left().value(), EdgeLabelEnum.INTERFACE, VertexTypeEnum.INTERFACE); - if (status != StorageOperationStatus.OK) { - return Either.right(status); + Map<String, InterfaceDataDefinition> interfaceDataDefinitionMap = componentEither.left().value(); + if (MapUtils.isEmpty(interfaceDataDefinitionMap)) { + statusRes = removeToscaData(componentId, EdgeLabelEnum.INTERFACE, VertexTypeEnum.INTERFACE); + if (!statusRes.equals(StorageOperationStatus.OK)) { + return Either.right(statusRes); + } } - } - else { - Either<InterfaceDefinition, StorageOperationStatus> intUpdateStatus = updateInterface(componentId, interfaceDef); - if (intUpdateStatus.isRight() && !intUpdateStatus.right().value().equals(StorageOperationStatus.OK)) { - return Either.right(status); - } - } - } - return Either.left(operation); - } - - private StorageOperationStatus performUpdateToscaAction(boolean isUpdate, GraphVertex graphVertex, - List<ToscaDataDefinition> toscaDataList, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexLabel) { - if (isUpdate) { - return updateToscaDataOfToscaElement(graphVertex, edgeLabel, vertexLabel, toscaDataList, JsonPresentationFields.UNIQUE_ID); - } else { - return addToscaDataToToscaElement(graphVertex, edgeLabel, vertexLabel, toscaDataList, JsonPresentationFields.UNIQUE_ID); - } - } - private void getUpdatedInterfaceDef(InterfaceDefinition interfaceDef, Operation operation, String operationId){ - Map<String, Operation> operationMap = interfaceDef.getOperationsMap(); - if(operation != null){ - operationMap.put(operationId, operation); - interfaceDef.setOperationsMap(operationMap); + return Either.left(interfacesToDelete); } - else { - operationMap.remove(operationId); - interfaceDef.setOperationsMap(operationMap); - } - } - -} - +}
\ No newline at end of file diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java index 9a87874b2a..3bdec2a30a 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/operations/TopologyTemplateOperation.java @@ -44,7 +44,6 @@ import org.openecomp.sdc.be.model.category.CategoryDefinition; import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement; import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum; -import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum; import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter; import org.openecomp.sdc.be.model.operations.StorageException; import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus; @@ -729,15 +728,6 @@ public class TopologyTemplateOperation extends ToscaElementOperation { if (assosiateElementToData.isRight()) { return assosiateElementToData.right().value(); } - else { - Map<String, OperationDataDefinition> operationMap = interfaceMap.values().stream().filter(op -> MapUtils.isNotEmpty(op.getOperations())).flatMap(a -> a.getOperations().entrySet().stream()).collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); - if(MapUtils.isNotEmpty(operationMap)) { - Either<GraphVertex, StorageOperationStatus> assosiateOpToInterface = associateElementToData(assosiateElementToData.left().value(), VertexTypeEnum.INTERFACE_OPERATION, EdgeLabelEnum.INTERFACE_OPERATION, operationMap); - if (assosiateOpToInterface.isRight()) { - return assosiateOpToInterface.right().value(); - } - } - } } return StorageOperationStatus.OK; } @@ -1062,25 +1052,17 @@ public class TopologyTemplateOperation extends ToscaElementOperation { log.debug("Failed to disassociate service api artifacts for {} error {}", toscaElementVertex.getUniqueId(), status); Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } - - Either<GraphVertex, TitanOperationStatus> getInterfaceVertex = titanDao.getChildVertex(toscaElementVertex, EdgeLabelEnum.INTERFACE, JsonParseFlagEnum.NoParse); - if (getInterfaceVertex.isLeft()) { - status = titanDao.disassociateAndDeleteLast(getInterfaceVertex.left().value(), Direction.OUT, EdgeLabelEnum.INTERFACE_OPERATION); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate interface operations for {} error {}", getInterfaceVertex.left().value().getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - else { - status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE); - if (status != TitanOperationStatus.OK) { - log.debug("Failed to disassociate interfaces for {} error {}", toscaElementVertex.getUniqueId(), status); - Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); - } - } - + status = titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INTERFACE); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate interfaces for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); } - titanDao.disassociateAndDeleteLast(toscaElementVertex, Direction.OUT, EdgeLabelEnum.INSTANCE_ARTIFACTS); + if (status != TitanOperationStatus.OK) { + log.debug("Failed to disassociate instance artifact for {} error {}", toscaElementVertex.getUniqueId(), status); + Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status)); + } + toscaElementVertex.getVertex().remove(); log.trace("Tosca element vertex for {} was removed", toscaElementVertex.getUniqueId()); diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtils.java b/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtils.java deleted file mode 100644 index feef31cbc1..0000000000 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtils.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ -package org.openecomp.sdc.be.model.jsontitan.utils; - -import org.apache.commons.collections.CollectionUtils; -import org.openecomp.sdc.be.model.InterfaceDefinition; - -import java.util.Collection; -import java.util.Formatter; -import java.util.Optional; -import java.util.stream.Collectors; -import org.openecomp.sdc.common.util.ValidationUtils; - -public class InterfaceUtils { - - public static final String INTERFACE_TOSCA_RESOURCE_NAME = "org.openecomp.interfaces.node.lifecycle.%s"; - - public static final Optional<InterfaceDefinition> getInterfaceDefinitionFromToscaName( - Collection<InterfaceDefinition> interfaces, - String componentName) { - if (CollectionUtils.isEmpty(interfaces)) { - return Optional.empty(); - } - - String toscaName = createInterfaceToscaResourceName(componentName); - return interfaces.stream().filter( - interfaceDefinition -> interfaceDefinition.getToscaResourceName() != null && interfaceDefinition - .getToscaResourceName().equals(toscaName)).findAny(); - } - - public static Collection<InterfaceDefinition> getInterfaceDefinitionListFromToscaName(Collection<InterfaceDefinition> interfaces, - String componentName) { - if (CollectionUtils.isEmpty(interfaces)) { - return CollectionUtils.EMPTY_COLLECTION; - } - - String toscaName = createInterfaceToscaResourceName(componentName); - return interfaces.stream().filter( - interfaceDefinition -> interfaceDefinition.getToscaResourceName() != null && interfaceDefinition - .getToscaResourceName().equals(toscaName)).collect(Collectors.toList()); - } - - public static String createInterfaceToscaResourceName(String componentName) { - StringBuilder sb = new StringBuilder(); - try (Formatter formatter = new Formatter(sb)) { - return formatter.format(INTERFACE_TOSCA_RESOURCE_NAME, ValidationUtils.convertToSystemName(componentName)).toString(); - } - } -} diff --git a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java index 0090f86f0e..43df6da2e6 100644 --- a/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java +++ b/catalog-model/src/main/java/org/openecomp/sdc/be/ui/model/UiComponentDataTransfer.java @@ -20,7 +20,7 @@ package org.openecomp.sdc.be.ui.model; -import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationDataDefinition; + import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.model.AdditionalInformationDefinition; import org.openecomp.sdc.be.model.ArtifactDefinition; @@ -78,17 +78,8 @@ public class UiComponentDataTransfer { protected List<AdditionalInformationDefinition> additionalInformation; - private Map<String, InterfaceOperationDataDefinition> interfaceOperations; private Map<String, InterfaceDefinition> interfaces; - public Map<String, InterfaceOperationDataDefinition> getInterfaceOperations() { - return interfaceOperations; - } - - public void setInterfaceOperations(Map<String, InterfaceOperationDataDefinition> interfaceOperations) { - this.interfaceOperations = interfaceOperations; - } - public Map<String, InterfaceDefinition> getInterfaces() { return interfaces; } diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java index 2ecb4b444c..0d5614f176 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/ResourceTest.java @@ -3,7 +3,6 @@ package org.openecomp.sdc.be.model; import mockit.Deencapsulation; import org.junit.Assert; import org.junit.Test; -import org.openecomp.sdc.be.datatypes.elements.InterfaceOperationDataDefinition; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.unittests.utils.ModelConfDependentTest; diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfacesOperationTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperationTest.java index 375208d24e..fe2ea209f9 100644 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfacesOperationTest.java +++ b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/operations/InterfaceOperationTest.java @@ -6,6 +6,7 @@ import static org.junit.Assert.assertTrue; import fj.data.Either; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -48,35 +49,27 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:application-context-test.xml") -public class InterfacesOperationTest extends ModelTestBase { - @Resource - protected TitanDao titanDao; - - @Resource - private InterfaceOperation interfaceOperation; - - @Resource - protected NodeTypeOperation nodeTypeOperation; - - @Resource - protected TopologyTemplateOperation topologyTemplateOperation; - - @Resource - private ToscaElementLifecycleOperation lifecycleOperation; +public class InterfaceOperationTest extends ModelTestBase { private static final String RESOURCE_NAME = "Resource Name"; private static final String RESOURCE_ID = "resourceID"; - private static final String SERVICE_NAME = "Service Name"; private static final String SERVICE_ID = "serviceID"; - private final String categoryName = "category"; private final String subcategory = "mycategory"; - - private GraphVertex ownerVertex; - private final Service service = createService(); private final org.openecomp.sdc.be.model.Resource resource = createResource(); + @Resource + protected TitanDao titanDao; + @Resource + protected NodeTypeOperation nodeTypeOperation; + @Resource + protected TopologyTemplateOperation topologyTemplateOperation; + @Resource + private InterfaceOperation interfaceOperation; + @Resource + private ToscaElementLifecycleOperation lifecycleOperation; + private GraphVertex ownerVertex; @BeforeClass public static void initInterfacesOperation() { @@ -96,165 +89,35 @@ public class InterfacesOperationTest extends ModelTestBase { createTopologyTemplate("firstService"); } - @After - public void cleanAfter() { - GraphTestUtils.clearGraph(titanDao); - } - - @Test - public void testAddInterface_Service(){testAddInterface(service);} - - @Test - public void testAddInterface_Resource(){testAddInterface(resource);} - - @Test - public void testUpdateInterface_Service(){testUpdateInterface(service);} - - @Test - public void testUpdateInterface_Resource(){testUpdateInterface(resource);} - - @Test - public void testAddInterfaceOperation_Service(){testAddInterfaceOperation(service);} - - @Test - public void testAddInterfaceOperation_Resource(){testAddInterfaceOperation(resource);} - - @Test - public void testUpdateInterfaceOperation_Service(){testUpdateInterfaceOperation(service);} - - @Test - public void testUpdateInterfaceOperation_Resource(){testUpdateInterfaceOperation(resource);} - - @Test - public void testDeleteInterfaceOperation_Service(){testDeleteInterfaceOperation(service);} - - @Test - public void testDeleteInterfaceOperation_Resource(){testDeleteInterfaceOperation(resource);} - - @Test - public void testUpdateInterfaceShouldFailWhenNOtCreatedFirst() { - Component component = createResource(); - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - interfaceDefinition.setOperationsMap(createMockOperationMap()); - Either<InterfaceDefinition, StorageOperationStatus> res = interfaceOperation.updateInterface(component.getUniqueId(), - interfaceDefinition); - Assert.assertTrue(res.isRight()); - } - - private void testAddInterface(Component component) { - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - Either<InterfaceDefinition, StorageOperationStatus> res = interfaceOperation.addInterface(component.getUniqueId(), - interfaceDefinition); - Assert.assertTrue(res.isLeft()); - } - - private void testUpdateInterface(Component component) { - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - interfaceDefinition.setOperationsMap(createMockOperationMap()); - Either<InterfaceDefinition, StorageOperationStatus> res = interfaceOperation.addInterface(component.getUniqueId(), interfaceDefinition); - Assert.assertTrue(res.isLeft()); - InterfaceDefinition value = res.left().value(); - String new_description = "New Description"; - value.setDescription(new_description); - res = interfaceOperation.updateInterface(component.getUniqueId(), interfaceDefinition); - assertTrue(res.isLeft()); - assertEquals(new_description,res.left().value().getDescription()); - } - - private void testAddInterfaceOperation(Component component) { - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - Either<InterfaceDefinition, StorageOperationStatus> res = interfaceOperation.addInterface(component.getUniqueId(), interfaceDefinition); - Assert.assertTrue(res.isLeft()); - InterfaceDefinition value = res.left().value(); - Operation op = createMockOperation(); - Either<Operation, StorageOperationStatus> addInterfaceOperationRes = interfaceOperation.addInterfaceOperation(component.getUniqueId(), value, op); - assertTrue(addInterfaceOperationRes.isLeft()); - } - - private void testUpdateInterfaceOperation(Component component) { - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - Either<InterfaceDefinition, StorageOperationStatus> res = interfaceOperation.addInterface(component.getUniqueId(), interfaceDefinition); - Assert.assertTrue(res.isLeft()); - InterfaceDefinition value = res.left().value(); - Operation op = createMockOperation(); - Either<Operation, StorageOperationStatus> addInterfaceOperationRes = interfaceOperation.addInterfaceOperation(component.getUniqueId(), value, op); - Assert.assertTrue(addInterfaceOperationRes.isLeft()); - Operation resultOp = addInterfaceOperationRes.left().value(); - resultOp.setName("New_Create"); - Either<Operation, StorageOperationStatus> updateInterfaceOperationRes = interfaceOperation.updateInterfaceOperation(component.getUniqueId(), value, resultOp); - assertTrue(updateInterfaceOperationRes.isLeft()); - assertEquals("New_Create", updateInterfaceOperationRes.left().value().getName()); - } - - private void testDeleteInterfaceOperation(Component component) { - InterfaceDefinition interfaceDefinition = buildInterfaceDefinition(); - Either<InterfaceDefinition, StorageOperationStatus> res = interfaceOperation.addInterface(component.getUniqueId(), interfaceDefinition); - Assert.assertTrue(res.isLeft()); - InterfaceDefinition value = res.left().value(); - Operation op = createMockOperation(); - Either<Operation, StorageOperationStatus> addInterfaceOperationRes = interfaceOperation.addInterfaceOperation(component.getUniqueId(), value, op); - Assert.assertTrue(addInterfaceOperationRes.isLeft()); - Operation resultOp = addInterfaceOperationRes.left().value(); - Either<Operation, StorageOperationStatus> deleteInterfaceOperationRes = interfaceOperation.deleteInterfaceOperation(component.getUniqueId(), value, resultOp.getUniqueId()); - assertTrue(deleteInterfaceOperationRes.isLeft()); - } - - private InterfaceDefinition buildInterfaceDefinition() { - InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); - interfaceDefinition.setType("tosca.interfaces.standard"); - interfaceDefinition.setCreationDate(101232L); - return interfaceDefinition; - } - - private org.openecomp.sdc.be.model.Resource createResource() { - org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); - resource.setUniqueId(RESOURCE_ID); - resource.setName(RESOURCE_NAME); - resource.setDescription("My short description"); - resource.setInterfaces(createMockInterfaceDefinition()); - return resource; - } + private void createUsers() { + GraphVertex ownerV = new GraphVertex(VertexTypeEnum.USER); + ownerV.setUniqueId("user1"); - private Service createService() { - Service service = new Service(); - service.setUniqueId(SERVICE_ID); - service.setName(SERVICE_NAME); - service.setDescription("My short description"); - service.setInterfaces(createMockInterfaceDefinition()); - return service; - } + Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(); + metadataProperties.put(GraphPropertyEnum.USERID, ownerV.getUniqueId()); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, "user1"); + ownerV.setMetadataProperties(metadataProperties); + ownerV.updateMetadataJsonWithCurrentMetadataProperties(); + ownerV.setJson(new HashMap<>()); + Either<GraphVertex, TitanOperationStatus> createUserRes = titanDao.createVertex(ownerV); - private InterfaceDefinition createInterface(String uniqueID, String description, String type, String toscaResourceName, - Map<String, Operation> op) { - InterfaceDefinition id = new InterfaceDefinition(); - id.setType(type); - id.setDescription(description); - id.setUniqueId(uniqueID); - id.setToscaResourceName(toscaResourceName); - id.setOperationsMap(op); - return id; - } + ownerVertex = createUserRes.left().value(); - private Map<String, InterfaceDefinition> createMockInterfaceDefinition() { - Map<String, Operation> operationMap = createMockOperationMap(); - Map<String, InterfaceDefinition> interfaceDefinitionMap = new HashMap<>(); - interfaceDefinitionMap.put("int1", createInterface("int1", "Interface 1", - "lifecycle", "tosca", operationMap)); - return interfaceDefinitionMap; - } + GraphVertex modifierV = new GraphVertex(VertexTypeEnum.USER); + modifierV.setUniqueId("user2"); - private Map<String, Operation> createMockOperationMap() { - Map<String, Operation> operationMap = new HashMap<>(); - operationMap.put("op1", createMockOperation()); - return operationMap; - } + metadataProperties = new HashMap<>(); + metadataProperties.put(GraphPropertyEnum.USERID, modifierV.getUniqueId()); + metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); + metadataProperties.put(GraphPropertyEnum.NAME, "user2"); + modifierV.setMetadataProperties(metadataProperties); + modifierV.updateMetadataJsonWithCurrentMetadataProperties(); + modifierV.setJson(new HashMap<>()); + createUserRes = titanDao.createVertex(modifierV); + createUserRes.left().value(); - private Operation createMockOperation() { - Operation operation = new Operation(); - operation.setDefinition(false); - operation.setName("create"); - operation.setUniqueId("op1"); - return operation; + lifecycleOperation.findUser(ownerVertex.getUniqueId()); } private void createResourceCategory() { @@ -265,7 +128,8 @@ public class InterfacesOperationTest extends ModelTestBase { metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_CATEGORY.getName()); metadataProperties.put(GraphPropertyEnum.NAME, categoryName); - metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + metadataProperties + .put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); cat.setMetadataProperties(metadataProperties); cat.updateMetadataJsonWithCurrentMetadataProperties(); @@ -276,13 +140,15 @@ public class InterfacesOperationTest extends ModelTestBase { metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, subCatId); metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.RESOURCE_SUBCATEGORY.getName()); metadataProperties.put(GraphPropertyEnum.NAME, subcategory); - metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); + metadataProperties + .put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(subcategory)); subCat.setMetadataProperties(metadataProperties); subCat.updateMetadataJsonWithCurrentMetadataProperties(); Either<GraphVertex, TitanOperationStatus> catRes = titanDao.createVertex(cat); Either<GraphVertex, TitanOperationStatus> subCatRes = titanDao.createVertex(subCat); - titanDao.createEdge(catRes.left().value().getVertex(), subCatRes.left().value().getVertex(), EdgeLabelEnum.SUB_CATEGORY, new HashMap<>()); + titanDao.createEdge(catRes.left().value().getVertex(), subCatRes.left().value().getVertex(), + EdgeLabelEnum.SUB_CATEGORY, new HashMap<>()); } private void createServiceCategory() { @@ -293,32 +159,64 @@ public class InterfacesOperationTest extends ModelTestBase { metadataProperties.put(GraphPropertyEnum.UNIQUE_ID, catId); metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.SERVICE_CATEGORY.getName()); metadataProperties.put(GraphPropertyEnum.NAME, categoryName); - metadataProperties.put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); + metadataProperties + .put(GraphPropertyEnum.NORMALIZED_NAME, ValidationUtils.normalizeCategoryName4Uniqueness(categoryName)); cat.setMetadataProperties(metadataProperties); cat.updateMetadataJsonWithCurrentMetadataProperties(); titanDao.createVertex(cat); } - private void createTopologyTemplate(String name) { - TopologyTemplate service = new TopologyTemplate(); + private void createRootNodeType() { + NodeType vf = new NodeType(); String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); - service.setUniqueId(uniqueId); - service.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); - service.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), name); - service.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); - service.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); - service.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); - service.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); + vf.setUniqueId(uniqueId); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); + vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), "root"); + vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); + vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "1.0"); + vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VFC.name()); + vf.getMetadata() + .put(JsonPresentationFields.LIFECYCLE_STATE.getPresentation(), LifecycleStateEnum.CERTIFIED.name()); + vf.getMetadata().put(JsonPresentationFields.TOSCA_RESOURCE_NAME.getPresentation(), "root"); + vf.getMetadata().put(JsonPresentationFields.HIGHEST_VERSION.getPresentation(), true); + List<CategoryDefinition> categories = new ArrayList<>(); CategoryDefinition cat = new CategoryDefinition(); categories.add(cat); cat.setName(categoryName); - service.setCategories(categories); + List<SubCategoryDefinition> subCategories = new ArrayList<>(); + SubCategoryDefinition subCat = new SubCategoryDefinition(); + subCat.setName(subcategory); + subCategories.add(subCat); + cat.setSubcategories(subCategories); + vf.setCategories(categories); - service.setComponentType(ComponentTypeEnum.SERVICE); - Either<TopologyTemplate, StorageOperationStatus> createRes = topologyTemplateOperation.createTopologyTemplate(service); - Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createRes.left().value().getUniqueId()); + List<String> derivedFrom = new ArrayList<>(); + vf.setDerivedFrom(derivedFrom); + + Map<String, PropertyDataDefinition> properties = new HashMap<>(); + PropertyDataDefinition prop1 = new PropertyDataDefinition(); + prop1.setName("derived1"); + prop1.setDefaultValue("deriveddef1"); + properties.put("derived1", prop1); + + PropertyDataDefinition prop2 = new PropertyDataDefinition(); + prop2.setUniqueId("derived2"); + prop2.setName("deriveddef2"); + properties.put("derived2", prop2); + PropertyDataDefinition prop3 = new PropertyDataDefinition(); + prop3.setName("derived3"); + prop3.setDefaultValue("deriveddef3"); + properties.put("derived3", prop3); + + vf.setProperties(properties); + vf.setComponentType(ComponentTypeEnum.RESOURCE); + Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf); + + Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = + titanDao.getVertexById(createVFRes.left().value().getUniqueId()); getNodeTyeRes.left().value(); } @@ -347,11 +245,6 @@ public class InterfacesOperationTest extends ModelTestBase { vf.setDerivedFrom(derivedFrom); vf.setComponentType(ComponentTypeEnum.RESOURCE); - Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf); - - Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); - - GraphVertex vfVertex = getNodeTyeRes.left().value(); List<PropertyDataDefinition> addProperties = new ArrayList<>(); PropertyDataDefinition prop11 = new PropertyDataDefinition(); @@ -365,22 +258,30 @@ public class InterfacesOperationTest extends ModelTestBase { prop22.setDefaultValue("def22"); addProperties.add(prop22); - StorageOperationStatus status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, addProperties, JsonPresentationFields.NAME); - assertSame(status, StorageOperationStatus.OK); + Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf); + Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = + titanDao.getVertexById(createVFRes.left().value().getUniqueId()); + GraphVertex vfVertex = getNodeTyeRes.left().value(); + StorageOperationStatus status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, + VertexTypeEnum.PROPERTIES, addProperties, JsonPresentationFields.NAME); + assertSame(StorageOperationStatus.OK, status); PropertyDataDefinition prop33 = new PropertyDataDefinition(); prop33.setName("prop33"); prop33.setDefaultValue("def33"); - status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop33, JsonPresentationFields.NAME); - assertSame(status, StorageOperationStatus.OK); + status = nodeTypeOperation + .addToscaDataToToscaElement(vfVertex, EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, + prop33, JsonPresentationFields.NAME); + assertSame(StorageOperationStatus.OK, status); PropertyDataDefinition prop44 = new PropertyDataDefinition(); prop44.setName("prop44"); prop44.setDefaultValue("def44"); - status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex.getUniqueId(), EdgeLabelEnum.PROPERTIES, VertexTypeEnum.PROPERTIES, prop44, JsonPresentationFields.NAME); - assertSame(status, StorageOperationStatus.OK); + status = nodeTypeOperation.addToscaDataToToscaElement(vfVertex.getUniqueId(), EdgeLabelEnum.PROPERTIES, + VertexTypeEnum.PROPERTIES, prop44, JsonPresentationFields.NAME); + assertSame(StorageOperationStatus.OK, status); PropertyDataDefinition capProp = new PropertyDataDefinition(); capProp.setName("capProp"); @@ -392,96 +293,200 @@ public class InterfacesOperationTest extends ModelTestBase { Map<String, MapDataDefinition> capProps = new HashMap<>(); capProps.put("capName", dataToCreate); - nodeTypeOperation.associateElementToData( - vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); + nodeTypeOperation.associateElementToData(vfVertex, VertexTypeEnum.CAPABILITIES_PROPERTIES, + EdgeLabelEnum.CAPABILITIES_PROPERTIES, capProps); List<String> pathKeys = new ArrayList<>(); pathKeys.add("capName"); capProp.setDefaultValue("BBBB"); - nodeTypeOperation.updateToscaDataDeepElementOfToscaElement(vfVertex, EdgeLabelEnum.CAPABILITIES_PROPERTIES, VertexTypeEnum.CAPABILITIES_PROPERTIES, capProp, pathKeys, JsonPresentationFields.NAME); + nodeTypeOperation.updateToscaDataDeepElementOfToscaElement(vfVertex, EdgeLabelEnum.CAPABILITIES_PROPERTIES, + VertexTypeEnum.CAPABILITIES_PROPERTIES, capProp, pathKeys, JsonPresentationFields.NAME); } - private void createRootNodeType() { - NodeType vf = new NodeType(); + private void createTopologyTemplate(String name) { + TopologyTemplate service = new TopologyTemplate(); String uniqueId = UniqueIdBuilder.buildResourceUniqueId(); - vf.setUniqueId(uniqueId); - vf.setComponentType(ComponentTypeEnum.RESOURCE); - vf.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); - vf.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), "root"); - vf.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); - vf.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "1.0"); - vf.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VFC.name()); - vf.getMetadata().put(JsonPresentationFields.LIFECYCLE_STATE.getPresentation(), LifecycleStateEnum.CERTIFIED.name()); - vf.getMetadata().put(JsonPresentationFields.TOSCA_RESOURCE_NAME.getPresentation(), "root"); - vf.getMetadata().put(JsonPresentationFields.HIGHEST_VERSION.getPresentation(), true); - + service.setUniqueId(uniqueId); + service.setCreatorUserId((String) ownerVertex.getMetadataProperty(GraphPropertyEnum.USERID)); + service.getMetadata().put(JsonPresentationFields.NAME.getPresentation(), name); + service.getMetadata().put(JsonPresentationFields.UNIQUE_ID.getPresentation(), uniqueId); + service.getMetadata().put(JsonPresentationFields.VERSION.getPresentation(), "0.1"); + service.getMetadata().put(JsonPresentationFields.TYPE.getPresentation(), ResourceTypeEnum.VF.name()); + service.getMetadata().put(JsonPresentationFields.COMPONENT_TYPE.getPresentation(), ComponentTypeEnum.RESOURCE); List<CategoryDefinition> categories = new ArrayList<>(); CategoryDefinition cat = new CategoryDefinition(); categories.add(cat); cat.setName(categoryName); - List<SubCategoryDefinition> subCategories = new ArrayList<>(); - SubCategoryDefinition subCat = new SubCategoryDefinition(); - subCat.setName(subcategory); - subCategories.add(subCat); - cat.setSubcategories(subCategories); - vf.setCategories(categories); + service.setCategories(categories); - List<String> derivedFrom = new ArrayList<>(); - vf.setDerivedFrom(derivedFrom); + service.setComponentType(ComponentTypeEnum.SERVICE); + Either<TopologyTemplate, StorageOperationStatus> createRes = + topologyTemplateOperation.createTopologyTemplate(service); + Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = + titanDao.getVertexById(createRes.left().value().getUniqueId()); - Map<String, PropertyDataDefinition> properties = new HashMap<>(); - PropertyDataDefinition prop1 = new PropertyDataDefinition(); - prop1.setName("derived1"); - prop1.setDefaultValue("deriveddef1"); - properties.put("derived1", prop1); + getNodeTyeRes.left().value(); + } - PropertyDataDefinition prop2 = new PropertyDataDefinition(); - prop2.setUniqueId("derived2"); - prop2.setName("deriveddef2"); - properties.put("derived2", prop2); + @After + public void cleanAfter() { + GraphTestUtils.clearGraph(titanDao); + } - PropertyDataDefinition prop3 = new PropertyDataDefinition(); - prop3.setName("derived3"); - prop3.setDefaultValue("deriveddef3"); - properties.put("derived3", prop3); + @Test + public void testAddInterface_Service() { + testAddSingleInterface(service); + } - vf.setProperties(properties); - vf.setComponentType(ComponentTypeEnum.RESOURCE); - Either<NodeType, StorageOperationStatus> createVFRes = nodeTypeOperation.createNodeType(vf); + private void testAddSingleInterface(Component component) { + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition("1"); + Either<List<InterfaceDefinition>, StorageOperationStatus> res = interfaceOperation + .addInterfaces(component.getUniqueId(), + Collections.singletonList( + interfaceDefinition)); + Assert.assertTrue(res.isLeft()); + Assert.assertEquals("1", res.left().value().get(0).getUniqueId()); + } - Either<GraphVertex, TitanOperationStatus> getNodeTyeRes = titanDao.getVertexById(createVFRes.left().value().getUniqueId()); - getNodeTyeRes.left().value(); + private InterfaceDefinition buildInterfaceDefinition(String uniqueId) { + InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); + interfaceDefinition.setType("tosca.interfaces.standard"); + interfaceDefinition.setUniqueId(uniqueId); + interfaceDefinition.setOperationsMap(createMockOperationMap()); + return interfaceDefinition; } - private void createUsers() { - GraphVertex ownerV = new GraphVertex(VertexTypeEnum.USER); - ownerV.setUniqueId("user1"); + private Map<String, Operation> createMockOperationMap() { + Map<String, Operation> operationMap = new HashMap<>(); + operationMap.put("op1", createMockOperation()); + return operationMap; + } - Map<GraphPropertyEnum, Object> metadataProperties = new HashMap<>(); - metadataProperties.put(GraphPropertyEnum.USERID, ownerV.getUniqueId()); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, "user1"); - ownerV.setMetadataProperties(metadataProperties); - ownerV.updateMetadataJsonWithCurrentMetadataProperties(); - ownerV.setJson(new HashMap<>()); - Either<GraphVertex, TitanOperationStatus> createUserRes = titanDao.createVertex(ownerV); + private Operation createMockOperation() { + Operation operation = new Operation(); + operation.setDefinition(false); + operation.setName("create"); + operation.setUniqueId("op1"); + return operation; + } - ownerVertex = createUserRes.left().value(); + @Test + public void testAddInterface_Resource() { + testAddMultipleInterface(resource); + } - GraphVertex modifierV = new GraphVertex(VertexTypeEnum.USER); - modifierV.setUniqueId("user2"); + private void testAddMultipleInterface(Component component) { + InterfaceDefinition interfaceDefinition1 = buildInterfaceDefinition("1"); + InterfaceDefinition interfaceDefinition2 = buildInterfaceDefinition("2"); + List<InterfaceDefinition> interfaceDefinitions = new ArrayList<>(); + interfaceDefinitions.add(interfaceDefinition1); + interfaceDefinitions.add(interfaceDefinition2); + Either<List<InterfaceDefinition>, StorageOperationStatus> res = + interfaceOperation.addInterfaces(component.getUniqueId(), interfaceDefinitions); + Assert.assertTrue(res.isLeft()); + Assert.assertEquals(2, res.left().value().size()); + } - metadataProperties = new HashMap<>(); - metadataProperties.put(GraphPropertyEnum.USERID, modifierV.getUniqueId()); - metadataProperties.put(GraphPropertyEnum.LABEL, VertexTypeEnum.USER.getName()); - metadataProperties.put(GraphPropertyEnum.NAME, "user2"); - modifierV.setMetadataProperties(metadataProperties); - modifierV.updateMetadataJsonWithCurrentMetadataProperties(); - modifierV.setJson(new HashMap<>()); - createUserRes = titanDao.createVertex(modifierV); - createUserRes.left().value(); + @Test + public void testUpdateInterface_Service() { + testUpdateInterface(service); + } - lifecycleOperation.findUser(ownerVertex.getUniqueId()); + private void testUpdateInterface(Component component) { + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition("1"); + Either<List<InterfaceDefinition>, StorageOperationStatus> res = interfaceOperation + .addInterfaces(component.getUniqueId(), + Collections.singletonList( + interfaceDefinition)); + Assert.assertTrue(res.isLeft()); + List<InterfaceDefinition> value = res.left().value(); + InterfaceDefinition createdInterfaceDef = value.get(0); + String newDescription = "New Description"; + createdInterfaceDef.setDescription(newDescription); + res = interfaceOperation + .updateInterfaces(component.getUniqueId(), Collections.singletonList(createdInterfaceDef)); + assertTrue(res.isLeft()); + assertEquals(newDescription, res.left().value().get(0).getDescription()); + } + + @Test + public void testUpdateInterface_Resource() { + testUpdateInterface(resource); + } + + @Test + public void testDeleteInterface_Service() { + testDeleteInterface(service); + } + + private void testDeleteInterface(Component component) { + InterfaceDefinition interfaceDefinition = buildInterfaceDefinition("1"); + Either<List<InterfaceDefinition>, StorageOperationStatus> res = interfaceOperation + .addInterfaces(component.getUniqueId(), + Collections.singletonList( + interfaceDefinition)); + Assert.assertTrue(res.isLeft()); + List<InterfaceDefinition> value = res.left().value(); + Either<String, StorageOperationStatus> deleteInterfaceOperationRes = + interfaceOperation.deleteInterface(component.getUniqueId(), value.get(0).getUniqueId()); + assertTrue(deleteInterfaceOperationRes.isLeft()); + } + + @Test + public void testDeleteInterface_Resource() { + testDeleteInterface(resource); + } + + @Test + public void testUpdateInterfaceShouldFailWhenNOtCreatedFirst() { + Component component = createResource(); + InterfaceDefinition interfaceDefinition = buildInterfaceDefinitionWithoutOperation(); + interfaceDefinition.setOperationsMap(createMockOperationMap()); + Either<List<InterfaceDefinition>, StorageOperationStatus> res = interfaceOperation.updateInterfaces( + component.getUniqueId(), Collections.singletonList(interfaceDefinition)); + Assert.assertTrue(res.isRight()); + } + + private InterfaceDefinition buildInterfaceDefinitionWithoutOperation() { + InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); + interfaceDefinition.setType("tosca.interfaces.standard"); + return interfaceDefinition; + } + + private org.openecomp.sdc.be.model.Resource createResource() { + org.openecomp.sdc.be.model.Resource resource = new org.openecomp.sdc.be.model.Resource(); + resource.setUniqueId(RESOURCE_ID); + resource.setName(RESOURCE_NAME); + resource.setDescription("My short description"); + resource.setInterfaces(createMockInterfaceDefinition()); + return resource; + } + + private Service createService() { + Service service = new Service(); + service.setUniqueId(SERVICE_ID); + service.setName(SERVICE_NAME); + service.setDescription("My short description"); + service.setInterfaces(createMockInterfaceDefinition()); + return service; + } + + private Map<String, InterfaceDefinition> createMockInterfaceDefinition() { + Map<String, Operation> operationMap = createMockOperationMap(); + Map<String, InterfaceDefinition> interfaceDefinitionMap = new HashMap<>(); + interfaceDefinitionMap.put("int1", createInterface("int1", "Interface 1", "lifecycle", "tosca", operationMap)); + return interfaceDefinitionMap; + } + + private InterfaceDefinition createInterface(String uniqueId, String description, String type, + String toscaResourceName, Map<String, Operation> op) { + InterfaceDefinition id = new InterfaceDefinition(); + id.setType(type); + id.setDescription(description); + id.setUniqueId(uniqueId); + id.setToscaResourceName(toscaResourceName); + id.setOperationsMap(op); + return id; } @After diff --git a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtilsTest.java b/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtilsTest.java deleted file mode 100644 index fbf01bc91d..0000000000 --- a/catalog-model/src/test/java/org/openecomp/sdc/be/model/jsontitan/utils/InterfaceUtilsTest.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.openecomp.sdc.be.model.jsontitan.utils; - -import org.junit.Test; -import org.openecomp.sdc.be.model.InterfaceDefinition; -import org.openecomp.sdc.be.model.Operation; -import org.openecomp.sdc.be.model.Resource; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class InterfaceUtilsTest { - - private InterfaceUtils createTestSubject() { - return new InterfaceUtils(); - } - - - @Test - public void testGetInterfaceDefinitionFromToscaName() throws Exception { - Collection<InterfaceDefinition> interfaces = null; - String resourceName = ""; - Optional<InterfaceDefinition> result; - - // default test - result = InterfaceUtils.getInterfaceDefinitionFromToscaName(interfaces, resourceName); - } - - - @Test - public void testGetInterfaceDefinitionListFromToscaName() throws Exception { - Collection<InterfaceDefinition> interfaces = null; - String resourceName = ""; - Collection<InterfaceDefinition> result; - - // default test - result = InterfaceUtils.getInterfaceDefinitionListFromToscaName(interfaces, resourceName); - } - - - @Test - public void testCreateInterfaceToscaResourceName() throws Exception { - String resourceName = ""; - String result; - - // default test - result = InterfaceUtils.createInterfaceToscaResourceName(resourceName); - } -}
\ No newline at end of file diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java index c0505c2b3d..7ffd74772c 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceDataDefinition.java @@ -20,93 +20,91 @@ package org.openecomp.sdc.be.datatypes.elements; -import com.fasterxml.jackson.annotation.JsonCreator; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; +import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.TOSCA_RESOURCE_NAME; +import com.fasterxml.jackson.annotation.JsonCreator; import java.io.Serializable; import java.util.HashMap; import java.util.Map; - -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.TOSCA_RESOURCE_NAME; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; public class InterfaceDataDefinition extends ToscaDataDefinition implements Serializable { - @JsonCreator - public InterfaceDataDefinition() { - super(); - setOperations(new HashMap<>()); - } - - public InterfaceDataDefinition(String type, String description) { - this(); - setType(type); - setDescription(description); - - } - - public InterfaceDataDefinition(InterfaceDataDefinition p) { - setUniqueId(p.getUniqueId()); - setType(p.getType()); - setDescription(p.getDescription()); - setToscaResourceName(p.getToscaResourceName()); - setOperations(p.getOperations()); - } - - public String getUniqueId() { - return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID); - } - - public void setUniqueId(String uniqueId) { - setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId); - } - - public String getType() { - return (String) getToscaPresentationValue(JsonPresentationFields.TYPE); - } - - public void setType(String type) { - setToscaPresentationValue(JsonPresentationFields.TYPE, type); - } - - public Long getCreationDate() { - return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_DATE); - } - - public void setCreationDate(Long creationDate) { - setToscaPresentationValue(JsonPresentationFields.CREATION_DATE, creationDate); - } - - public Long getLastUpdateDate() { - return (Long) getToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE); - } - - public void setLastUpdateDate(Long lastUpdateDate) { - setToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); - } - - public String getDescription() { - return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION); - } - - public void setDescription(String description) { - setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description); - } - - public Map<String, OperationDataDefinition> getOperations() { - return (Map<String, OperationDataDefinition>) - getToscaPresentationValue(JsonPresentationFields.INTERFACE_OPERATION); - } - - public void setOperations(Map<String, OperationDataDefinition> operations) { - setToscaPresentationValue(JsonPresentationFields.INTERFACE_OPERATION, operations); - } - - public String getToscaResourceName() { - return (String) getToscaPresentationValue(TOSCA_RESOURCE_NAME); - } - - public void setToscaResourceName(String toscaResourceName) { - setToscaPresentationValue(TOSCA_RESOURCE_NAME, toscaResourceName); - } + public InterfaceDataDefinition(String type, String description) { + this(); + setType(type); + setDescription(description); + + } + + @JsonCreator + public InterfaceDataDefinition() { + super(); + setOperations(new HashMap<>()); + } + + public InterfaceDataDefinition(InterfaceDataDefinition p) { + setUniqueId(p.getUniqueId()); + setType(p.getType()); + setDescription(p.getDescription()); + setToscaResourceName(p.getToscaResourceName()); + setOperations(p.getOperations()); + } + + public String getUniqueId() { + return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID); + } + + public void setUniqueId(String uniqueId) { + setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId); + } + + public String getType() { + return (String) getToscaPresentationValue(JsonPresentationFields.TYPE); + } + + public void setType(String type) { + setToscaPresentationValue(JsonPresentationFields.TYPE, type); + } + + public String getDescription() { + return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION); + } + + public void setDescription(String description) { + setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description); + } + + public String getToscaResourceName() { + return (String) getToscaPresentationValue(TOSCA_RESOURCE_NAME); + } + + public Map<String, OperationDataDefinition> getOperations() { + return (Map<String, OperationDataDefinition>) getToscaPresentationValue(JsonPresentationFields.OPERATIONS); + } + + public void setOperations(Map<String, OperationDataDefinition> operations) { + setToscaPresentationValue(JsonPresentationFields.OPERATIONS, operations); + } + + public void setToscaResourceName(String toscaResourceName) { + setToscaPresentationValue(TOSCA_RESOURCE_NAME, toscaResourceName); + } + + public Long getCreationDate() { + return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_DATE); + } + + public void setCreationDate(Long creationDate) { + setToscaPresentationValue(JsonPresentationFields.CREATION_DATE, creationDate); + } + + public Long getLastUpdateDate() { + return (Long) getToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE); + } + + public void setLastUpdateDate(Long lastUpdateDate) { + setToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); + } } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationDataDefinition.java deleted file mode 100644 index 29093e9382..0000000000 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationDataDefinition.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ - -package org.openecomp.sdc.be.datatypes.elements; - - -import com.fasterxml.jackson.annotation.JsonCreator; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; - -import java.io.Serializable; - -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.ARTIFACT_UUID; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.DESCRIPTION; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_INPUT_PARAMETERS; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_OPERATION_TYPE; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_OUTPUT_PARAMETERS; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_WORKFLOW_ASSOCIATION_TYPE; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_WORKFLOW_ID; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_WORKFLOW_VERSION_ID; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.TOSCA_RESOURCE_NAME; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.UNIQUE_ID; - -public class InterfaceOperationDataDefinition extends ToscaDataDefinition implements Serializable { - - @JsonCreator - public InterfaceOperationDataDefinition() { - super(); - } - - public InterfaceOperationDataDefinition(InterfaceOperationDataDefinition iodd) { - super(); - setUniqueId(iodd.getUniqueId()); - setInputParams(iodd.getInputParams()); - setOutputParams(iodd.getOutputParams()); - setDescription(iodd.getDescription()); - setToscaResourceName(iodd.getToscaResourceName()); - setOperationType(iodd.getOperationType()); - setArtifactUUID(iodd.getArtifactUUID()); - setWorkflowId(iodd.getWorkflowId()); - setWorkflowVersionId(iodd.getWorkflowVersionId()); - setWorkflowAssociationType(iodd.getWorkflowAssociationType()); - } - - public ListDataDefinition<InterfaceOperationParamDataDefinition> getInputParams() { - return (ListDataDefinition<InterfaceOperationParamDataDefinition>) - getToscaPresentationValue(IO_INPUT_PARAMETERS); - } - public void setInputParams(ListDataDefinition<InterfaceOperationParamDataDefinition> - inputParams) { - setToscaPresentationValue(IO_INPUT_PARAMETERS, inputParams); - } - - public ListDataDefinition<InterfaceOperationParamDataDefinition> getOutputParams() { - return (ListDataDefinition<InterfaceOperationParamDataDefinition>) - getToscaPresentationValue(IO_OUTPUT_PARAMETERS); - } - public void setOutputParams(ListDataDefinition<InterfaceOperationParamDataDefinition> - outputParams) { - setToscaPresentationValue(IO_OUTPUT_PARAMETERS, outputParams); - } - - public String getUniqueId() { - return (String) getToscaPresentationValue(UNIQUE_ID); - } - public void setUniqueId(String uid) { - setToscaPresentationValue(UNIQUE_ID, uid); - } - - public String getDescription() { - return (String) getToscaPresentationValue(DESCRIPTION); - } - public void setDescription(String description) { - setToscaPresentationValue(DESCRIPTION, description); - } - - public String getOperationType() { - return (String) getToscaPresentationValue(IO_OPERATION_TYPE); - } - public void setOperationType(String operationType) { - setToscaPresentationValue(IO_OPERATION_TYPE, operationType); - } - - public String getToscaResourceName() { - return (String) getToscaPresentationValue(TOSCA_RESOURCE_NAME); - } - public void setToscaResourceName(String toscaResourceName) { - setToscaPresentationValue(TOSCA_RESOURCE_NAME, toscaResourceName); - } - - public String getWorkflowId(){ - return (String) getToscaPresentationValue(IO_WORKFLOW_ID); - } - public void setWorkflowId(String workflowId) { - setToscaPresentationValue(IO_WORKFLOW_ID, workflowId); - } - - public String getWorkflowVersionId() { - return (String) getToscaPresentationValue(IO_WORKFLOW_VERSION_ID); - } - public void setWorkflowVersionId(String workflowVersionId) { - setToscaPresentationValue(IO_WORKFLOW_VERSION_ID, workflowVersionId); - } - - public String getArtifactUUID() { - return (String) getToscaPresentationValue(ARTIFACT_UUID); - } - public void setArtifactUUID(String artifactUUID) { - setToscaPresentationValue(ARTIFACT_UUID, artifactUUID); - } - - public String getWorkflowAssociationType() { - return (String) getToscaPresentationValue(IO_WORKFLOW_ASSOCIATION_TYPE); - } - - public void setWorkflowAssociationType(String workflowAssociationType) { - setToscaPresentationValue(IO_WORKFLOW_ASSOCIATION_TYPE, workflowAssociationType); - } -} diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationParamDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationParamDataDefinition.java deleted file mode 100644 index b8372d6793..0000000000 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationParamDataDefinition.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright © 2016-2018 European Support Limited - * - * 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. - */ - -package org.openecomp.sdc.be.datatypes.elements; - -import com.fasterxml.jackson.annotation.JsonCreator; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; - -import java.io.Serializable; - -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_MANDATORY; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_PROPERTY; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_NAME; -import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_TYPE; - -public class InterfaceOperationParamDataDefinition extends ToscaDataDefinition implements Serializable { - - @JsonCreator - public InterfaceOperationParamDataDefinition() { - super(); - } - - public InterfaceOperationParamDataDefinition(InterfaceOperationParamDataDefinition iopdd) { - super(); - setName(iopdd.getName()); - setProperty(iopdd.getProperty()); - setMandatory(iopdd.getMandatory()); - setType(iopdd.getType()); - } - - public InterfaceOperationParamDataDefinition(String name, String property, boolean mandatory, String type) { - super(); - setName(name); - setProperty(property); - setMandatory(mandatory); - setType(type); - } - - //used for OperationOutputDefinition - public InterfaceOperationParamDataDefinition(String name, boolean mandatory, String type) { - super(); - setName(name); - setMandatory(mandatory); - setType(type); - } - - public String getName() { - return (String) getToscaPresentationValue(IO_NAME); - } - public void setName(String name) { - setToscaPresentationValue(IO_NAME, name); - } - - public String getProperty() { - return (String) getToscaPresentationValue(IO_PROPERTY); - } - public void setProperty(String property) { - setToscaPresentationValue(IO_PROPERTY, property); - } - - public Boolean getMandatory() { - return (Boolean) getToscaPresentationValue(IO_MANDATORY); - } - public void setMandatory(Boolean mandatory) { - setToscaPresentationValue(IO_MANDATORY, mandatory); - } - - public String getType() { - return (String) getToscaPresentationValue(IO_TYPE); - } - public void setType(String type) { - setToscaPresentationValue(IO_TYPE, type); - } -} diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java index 722d605743..84b6124b97 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/elements/OperationDataDefinition.java @@ -20,127 +20,127 @@ package org.openecomp.sdc.be.datatypes.elements; -import com.fasterxml.jackson.annotation.JsonCreator; -import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; -import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; - -import java.io.Serializable; - import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_WORKFLOW_ASSOCIATION_TYPE; import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_WORKFLOW_ID; import static org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields.IO_WORKFLOW_VERSION_ID; +import com.fasterxml.jackson.annotation.JsonCreator; +import java.io.Serializable; +import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields; +import org.openecomp.sdc.be.datatypes.tosca.ToscaDataDefinition; + public class OperationDataDefinition extends ToscaDataDefinition implements Serializable { - @JsonCreator - public OperationDataDefinition() { - super(); - } - - public OperationDataDefinition(String description) { - super(); - setDescription(description); - } - - public OperationDataDefinition(OperationDataDefinition p) { - setDescription(p.getDescription()); - setImplementation(p.getImplementation()); - setInputs(p.getInputs()); - setOutputs(p.getOutputs()); - setName(p.getName()); - setUniqueId(p.getUniqueId()); - setWorkflowId(p.getWorkflowId()); - setWorkflowVersionId(p.getWorkflowVersionId()); - setWorkflowAssociationType(p.getWorkflowAssociationType()); - } - - - public String getUniqueId() { - return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID); - } - - public void setUniqueId(String uniqueId) { - setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId); - } - - - public Long getCreationDate() { - return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_DATE); - } - - public void setCreationDate(Long creationDate) { - setToscaPresentationValue(JsonPresentationFields.CREATION_DATE, creationDate); - } - - public Long getLastUpdateDate() { - return (Long) getToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE); - } - - public void setLastUpdateDate(Long lastUpdateDate) { - setToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); - } - - public String getDescription() { - return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION); - } - - public void setDescription(String description) { - setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description); - } - - public ArtifactDataDefinition getImplementation() { - return (ArtifactDataDefinition) getToscaPresentationValue(JsonPresentationFields.OPERATION_IMPLEMENTATION); - } - - public void setImplementation(ArtifactDataDefinition implementation) { - setToscaPresentationValue(JsonPresentationFields.OPERATION_IMPLEMENTATION, implementation); - } - - public ListDataDefinition<OperationInputDefinition> getInputs() { - return (ListDataDefinition<OperationInputDefinition>) - getToscaPresentationValue(JsonPresentationFields.OPERATION_INPUT); - } - - public void setInputs(ListDataDefinition<OperationInputDefinition> inputs) { - setToscaPresentationValue(JsonPresentationFields.OPERATION_INPUT,inputs); - } - - public ListDataDefinition<OperationOutputDefinition> getOutputs() { - return (ListDataDefinition<OperationOutputDefinition>) - getToscaPresentationValue(JsonPresentationFields.OPERATION_OUTPUT); - } - - public void setOutputs(ListDataDefinition<OperationOutputDefinition> outputs) { - setToscaPresentationValue(JsonPresentationFields.OPERATION_OUTPUT, outputs); - } - public String getName() { - return (String) getToscaPresentationValue(JsonPresentationFields.NAME); - } - - public void setName(String name) { - setToscaPresentationValue(JsonPresentationFields.NAME, name); - } - - public String getWorkflowId(){ - return (String) getToscaPresentationValue(IO_WORKFLOW_ID); - } - public void setWorkflowId(String workflowId) { - setToscaPresentationValue(IO_WORKFLOW_ID, workflowId); - } - - public String getWorkflowVersionId() { - return (String) getToscaPresentationValue(IO_WORKFLOW_VERSION_ID); - } - public void setWorkflowVersionId(String workflowVersionId) { - setToscaPresentationValue(IO_WORKFLOW_VERSION_ID, workflowVersionId); - } - - public String getWorkflowAssociationType() { - return (String) getToscaPresentationValue(IO_WORKFLOW_ASSOCIATION_TYPE); - } - - public void setWorkflowAssociationType(String workflowAssociationType) { - setToscaPresentationValue(IO_WORKFLOW_ASSOCIATION_TYPE, workflowAssociationType); - } + @JsonCreator + public OperationDataDefinition() { + super(); + } + + public OperationDataDefinition(String description) { + super(); + setDescription(description); + } + + public OperationDataDefinition(OperationDataDefinition p) { + setDescription(p.getDescription()); + setImplementation(p.getImplementation()); + setInputs(p.getInputs()); + setOutputs(p.getOutputs()); + setName(p.getName()); + setUniqueId(p.getUniqueId()); + setWorkflowId(p.getWorkflowId()); + setWorkflowVersionId(p.getWorkflowVersionId()); + setWorkflowAssociationType(p.getWorkflowAssociationType()); + } + + public String getDescription() { + return (String) getToscaPresentationValue(JsonPresentationFields.DESCRIPTION); + } + + public void setDescription(String description) { + setToscaPresentationValue(JsonPresentationFields.DESCRIPTION, description); + } + + public ArtifactDataDefinition getImplementation() { + return (ArtifactDataDefinition) getToscaPresentationValue(JsonPresentationFields.OPERATION_IMPLEMENTATION); + } + + public void setImplementation(ArtifactDataDefinition implementation) { + setToscaPresentationValue(JsonPresentationFields.OPERATION_IMPLEMENTATION, implementation); + } + + public ListDataDefinition<OperationInputDefinition> getInputs() { + return (ListDataDefinition<OperationInputDefinition>) getToscaPresentationValue( + JsonPresentationFields.OPERATION_INPUTS); + } + + public void setInputs(ListDataDefinition<OperationInputDefinition> inputs) { + setToscaPresentationValue(JsonPresentationFields.OPERATION_INPUTS, inputs); + } + + public ListDataDefinition<OperationOutputDefinition> getOutputs() { + return (ListDataDefinition<OperationOutputDefinition>) getToscaPresentationValue( + JsonPresentationFields.OPERATION_OUTPUTS); + } + + public void setOutputs(ListDataDefinition<OperationOutputDefinition> outputs) { + setToscaPresentationValue(JsonPresentationFields.OPERATION_OUTPUTS, outputs); + } + + public String getName() { + return (String) getToscaPresentationValue(JsonPresentationFields.NAME); + } + + public String getUniqueId() { + return (String) getToscaPresentationValue(JsonPresentationFields.UNIQUE_ID); + } + + public void setUniqueId(String uniqueId) { + setToscaPresentationValue(JsonPresentationFields.UNIQUE_ID, uniqueId); + } + + public String getWorkflowId() { + return (String) getToscaPresentationValue(IO_WORKFLOW_ID); + } + + public void setWorkflowId(String workflowId) { + setToscaPresentationValue(IO_WORKFLOW_ID, workflowId); + } + + public String getWorkflowVersionId() { + return (String) getToscaPresentationValue(IO_WORKFLOW_VERSION_ID); + } + + public void setWorkflowVersionId(String workflowVersionId) { + setToscaPresentationValue(IO_WORKFLOW_VERSION_ID, workflowVersionId); + } + + public String getWorkflowAssociationType() { + return (String) getToscaPresentationValue(IO_WORKFLOW_ASSOCIATION_TYPE); + } + + public void setWorkflowAssociationType(String workflowAssociationType) { + setToscaPresentationValue(IO_WORKFLOW_ASSOCIATION_TYPE, workflowAssociationType); + } + + public void setName(String name) { + setToscaPresentationValue(JsonPresentationFields.NAME, name); + } + + public Long getCreationDate() { + return (Long) getToscaPresentationValue(JsonPresentationFields.CREATION_DATE); + } + + public void setCreationDate(Long creationDate) { + setToscaPresentationValue(JsonPresentationFields.CREATION_DATE, creationDate); + } + + public Long getLastUpdateDate() { + return (Long) getToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE); + } + + public void setLastUpdateDate(Long lastUpdateDate) { + setToscaPresentationValue(JsonPresentationFields.LAST_UPDATE_DATE, lastUpdateDate); + } } diff --git a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java index d5283c6dc3..40d6a70110 100644 --- a/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java +++ b/common-be/src/main/java/org/openecomp/sdc/be/datatypes/enums/JsonPresentationFields.java @@ -120,7 +120,7 @@ public enum JsonPresentationFields { CAPABILITY_SOURCES("capabilitySources", null), MAX_OCCURRENCES("maxOccurrences", null), MIN_OCCURRENCES("minOccurrences", null), - OWNER_TYPE ("ownerType", null), + OWNER_TYPE("ownerType",null), OWNER_NAME("ownerName", null), OWNER_ID("ownerId", null), LEFT_OCCURRENCES("leftOccurences", null), @@ -210,26 +210,15 @@ public enum JsonPresentationFields { IS_VSP_ARCHIVED("isVspArchived", GraphPropertyEnum.IS_VSP_ARCHIVED), CI_IS_ORIGIN_ARCHIVED("isOriginArchived", null), - //Interface Operation - IO_OPERATION_TYPE("operationType",null), - IO_INPUT_PARAMETERS("inputParams",null), - IO_OUTPUT_PARAMETERS("outputParams",null), - IO_NAME("name", null), - IO_MANDATORY("mandatory", null), - IO_TYPE("type", null), - IO_PROPERTY("property", null), - IO_WORKFLOW_ID("workflowId", null), - IO_WORKFLOW_VERSION_ID("workflowVersionId", null), + //Interface Operation + IO_WORKFLOW_ID("workflowId", null), + IO_WORKFLOW_VERSION_ID("workflowVersionId", null), IO_WORKFLOW_ASSOCIATION_TYPE("workflowAssociationType", null), - - //Interface - INTERFACE ("interface", null), - INTERFACE_OPERATION ("operation", null), - OPERATION_IMPLEMENTATION("operationImplementation",null), - OPERATION_INPUT("operationInput",null), - OPERATION_OUTPUT("operationOutput", null) - ; - + INTERFACES("interfaces", null), + OPERATIONS("operations", null), + OPERATION_IMPLEMENTATION("implementation",null), + OPERATION_INPUTS("inputs",null), + OPERATION_OUTPUTS("outputs", null); private String presentation; private GraphPropertyEnum storedAs; diff --git a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationDataDefinitionTest.java b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationDataDefinitionTest.java deleted file mode 100644 index e0e07fd259..0000000000 --- a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationDataDefinitionTest.java +++ /dev/null @@ -1,159 +0,0 @@ -package org.openecomp.sdc.be.datatypes.elements; - -import org.junit.Test; - -public class InterfaceOperationDataDefinitionTest { - - private InterfaceOperationDataDefinition createTestSubject() { - return new InterfaceOperationDataDefinition(); - } - - @Test - public void testCopyConstructor() throws Exception { - InterfaceOperationDataDefinition testSubject; - - // default test - testSubject = createTestSubject(); - new InterfaceOperationDataDefinition(testSubject); - } - - @Test - public void testGetInputParams() throws Exception { - InterfaceOperationDataDefinition testSubject; - ListDataDefinition<InterfaceOperationParamDataDefinition> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInputParams(); - } - - @Test - public void testSetInputParams() throws Exception { - InterfaceOperationDataDefinition testSubject; - ListDataDefinition<InterfaceOperationParamDataDefinition> inputParams = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInputParams(inputParams); - } - - @Test - public void testGetOutputParams() throws Exception { - InterfaceOperationDataDefinition testSubject; - ListDataDefinition<InterfaceOperationParamDataDefinition> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getOutputParams(); - } - - @Test - public void testSetOutputParams() throws Exception { - InterfaceOperationDataDefinition testSubject; - ListDataDefinition<InterfaceOperationParamDataDefinition> outputParams = null; - - // default test - testSubject = createTestSubject(); - testSubject.setOutputParams(outputParams); - } - - @Test - public void testGetUniqueId() throws Exception { - InterfaceOperationDataDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getUniqueId(); - } - - @Test - public void testSetUniqueId() throws Exception { - InterfaceOperationDataDefinition testSubject; - String uid = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setUniqueId(uid); - } - - @Test - public void testGetDescription() throws Exception { - InterfaceOperationDataDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDescription(); - } - - @Test - public void testSetDescription() throws Exception { - InterfaceOperationDataDefinition testSubject; - String description = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setDescription(description); - } - - @Test - public void testGetOperationType() throws Exception { - InterfaceOperationDataDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getOperationType(); - } - - @Test - public void testSetOperationType() throws Exception { - InterfaceOperationDataDefinition testSubject; - String operationType = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setOperationType(operationType); - } - - @Test - public void testGetToscaResourceName() throws Exception { - InterfaceOperationDataDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getToscaResourceName(); - } - - @Test - public void testSetToscaResourceName() throws Exception { - InterfaceOperationDataDefinition testSubject; - String toscaResourceName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setToscaResourceName(toscaResourceName); - } - - @Test - public void testGetArtifactUUID() throws Exception { - InterfaceOperationDataDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getArtifactUUID(); - } - - @Test - public void testSetArtifactUUID() throws Exception { - InterfaceOperationDataDefinition testSubject; - String artifactUUID = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setArtifactUUID(artifactUUID); - } -}
\ No newline at end of file diff --git a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationParamDataDefinitionTest.java b/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationParamDataDefinitionTest.java deleted file mode 100644 index e25adb3c2f..0000000000 --- a/common-be/src/test/java/org/openecomp/sdc/be/datatypes/elements/InterfaceOperationParamDataDefinitionTest.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.openecomp.sdc.be.datatypes.elements; - -import org.junit.Test; - -public class InterfaceOperationParamDataDefinitionTest { - - private InterfaceOperationParamDataDefinition createTestSubject() { - return new InterfaceOperationParamDataDefinition(); - } - - @Test - public void testOverloadConstructor() throws Exception { - InterfaceOperationParamDataDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - new InterfaceOperationParamDataDefinition(testSubject); - new InterfaceOperationParamDataDefinition("", "",true, ""); - } - - @Test - public void testGetParamName() throws Exception { - InterfaceOperationParamDataDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getName(); - } - - @Test - public void testSetParamName() throws Exception { - InterfaceOperationParamDataDefinition testSubject; - String paramName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setName(paramName); - } - - @Test - public void testGetParamId() throws Exception { - InterfaceOperationParamDataDefinition testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getProperty(); - } - - @Test - public void testSetParamId() throws Exception { - InterfaceOperationParamDataDefinition testSubject; - String paramId = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setProperty(paramId); - } -}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/features/InterfaceOperation/TestResourceInterfaceOperation.feature b/cucumber-js-test-apis-ci/features/InterfaceOperation/TestResourceInterfaceOperation.feature index ed09f2fb20..7a4105f443 100644 --- a/cucumber-js-test-apis-ci/features/InterfaceOperation/TestResourceInterfaceOperation.feature +++ b/cucumber-js-test-apis-ci/features/InterfaceOperation/TestResourceInterfaceOperation.feature @@ -4,25 +4,19 @@ Feature: Interface Operation Feature Given I want to create a VF Scenario: Test InterfaceOperation CRUD - #Create Operations + #Create Multiple operations Operations + When I want to create an Operation + When I want to create an Operation When I want to create an Operation - Then I want to check property "uniqueId" exists - And I want to create an Operation with workflow - Then I want to check property "uniqueId" exists - And I want to create an Operation - Then I want to check property "uniqueId" exists - When I want to create an Operation with input output - Then I want to check property "uniqueId" exists #List All Operations When I want to list Operations #Get Operation By OperationId When I want to get an Operation by Id - Then I want to check property "uniqueId" exists + #Update Operation When I want to update an Operation - Then I want to check property "uniqueId" exists #Delete Operation When I want to delete an Operation @@ -38,11 +32,8 @@ Feature: Interface Operation Feature Scenario: Test InterfaceOperation CREATE #Create Operations When I want to create an Operation - Then I want to check property "uniqueId" exists And I want to create an Operation - Then I want to check property "uniqueId" exists And I want to create an Operation - Then I want to check property "uniqueId" exists #List All Operations When I want to list Operations @@ -59,14 +50,11 @@ Feature: Interface Operation Feature Scenario: Test InterfaceOperation UPDATE #Create Operation When I want to create an Operation - Then I want to check property "uniqueId" exists #Get Operation By OperationId When I want to get an Operation by Id - Then I want to check property "uniqueId" exists #Update Operation When I want to update an Operation - Then I want to check property "uniqueId" exists #Checkin When I want to checkin this component @@ -80,11 +68,9 @@ Feature: Interface Operation Feature Scenario: Test InterfaceOperation DELETE #Create Operation When I want to create an Operation - Then I want to check property "uniqueId" exists #Get Operation By OperationId When I want to get an Operation by Id - Then I want to check property "uniqueId" exists #Delete Operation When I want to delete an Operation diff --git a/cucumber-js-test-apis-ci/features/InterfaceOperation/TestServiceInterfaceOperation.feature b/cucumber-js-test-apis-ci/features/InterfaceOperation/TestServiceInterfaceOperation.feature index 1ff0ba3f1b..72d56d5fc7 100644 --- a/cucumber-js-test-apis-ci/features/InterfaceOperation/TestServiceInterfaceOperation.feature +++ b/cucumber-js-test-apis-ci/features/InterfaceOperation/TestServiceInterfaceOperation.feature @@ -4,26 +4,19 @@ Feature: Interface Operation Feature Given I want to create a Service Scenario: Test InterfaceOperation CRUD - #Create Operations + #Create multiple operations Operations + When I want to create an Operation + When I want to create an Operation When I want to create an Operation - Then I want to check property "uniqueId" exists - And I want to create an Operation with workflow - Then I want to check property "uniqueId" exists - And I want to create an Operation - Then I want to check property "uniqueId" exists - When I want to create an Operation with input output - Then I want to check property "uniqueId" exists #List All Operations When I want to list Operations #Get Operation By OperationId When I want to get an Operation by Id - Then I want to check property "uniqueId" exists #Update Operation When I want to update an Operation - Then I want to check property "uniqueId" exists #Delete Operation When I want to delete an Operation diff --git a/cucumber-js-test-apis-ci/resources/json/createService.json b/cucumber-js-test-apis-ci/resources/json/createService.json new file mode 100644 index 0000000000..a76cc51dda --- /dev/null +++ b/cucumber-js-test-apis-ci/resources/json/createService.json @@ -0,0 +1,66 @@ +{ + "artifacts": {}, + "toscaArtifacts": {}, + "contactId": "cs0008", + "categories": [{ + "name": "Network L4+", + "normalizedName": "network l4+", + "uniqueId": "serviceNewCategory.network l4+", + "icons": ["network_l_4"], + "subcategories": null, + "version": null, + "ownerId": null, + "empty": false, + "type": null + }], + "description": "service1 for bdd", + "icon": "defaulticon", + "componentInstancesProperties": {}, + "componentInstancesAttributes": {}, + "name": "service1", + "tags": ["service1"], + "capabilities": {}, + "requirements": {}, + "deploymentArtifacts": {}, + "componentType": "SERVICE", + "projectCode": "010203", + "componentInstances": [], + "properties": [], + "inputs": [{ + "uniqueId": "03eeb10e-cf2a-41b8-9d8e-d2dbd094f9d4.test1_dasddas", + "type": "scalar-unit.size", + "required": false, + "definition": false, + "schema": { + "properties": {}, + "property": { + "type": "", + "required": false, + "definition": true, + "password": false, + "hidden": false, + "immutable": false, + "getInputProperty": false, + "empty": false + }, + "empty": false + }, + "password": false, + "name": "test1_dasddas", + "hidden": false, + "immutable": false, + "instanceUniqueId": "03eeb10e-cf2a-41b8-9d8e-d2dbd094f9d4", + "propertyId": "03eeb10e-cf2a-41b8-9d8e-d2dbd094f9d4.dasddas", + "parentUniqueId": "cs0008", + "schemaType": "", + "getInputProperty": false, + "ownerId": "cs0008", + "empty": false + }], + "attributes": [], + "forwardingPaths": {}, + "ecompGeneratedNaming": true, + "serviceApiArtifacts": {}, + "instantiationType": "A-la-carte", + "environmentContext": "General_Revenue-Bearing" +}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/resources/json/createVFWithoutCSAR.json b/cucumber-js-test-apis-ci/resources/json/createVFWithoutCSAR.json new file mode 100644 index 0000000000..dd8764f625 --- /dev/null +++ b/cucumber-js-test-apis-ci/resources/json/createVFWithoutCSAR.json @@ -0,0 +1,76 @@ +{ + "artifacts": {}, + "toscaArtifacts": {}, + "contactId": "cs0008", + "categories": [{ + "name": "Generic", + "normalizedName": "generic", + "uniqueId": "REPLACE CATEGORY VSP", + "icons": null, + "subcategories": [ + { + "name": "Abstract", + "normalizedName": "abstract", + "uniqueId": "REPLACE SUBCATEGORY VSP", + "icons": [ + "objectStorage", + "compute" + ], + "groupings": null, + "ownerId": null, + "empty": false + } + ], + "ownerId": null, + "empty": false + }], + "description": "vf_for_bdd", + "icon": "defaulticon", + "componentInstancesProperties": {}, + "componentInstancesAttributes": {}, + "name": "vf_for_bdd", + "tags": ["vf_for_bdd"], + "capabilities": {}, + "requirements": {}, + "deploymentArtifacts": {}, + "componentType": "RESOURCE", + "vendorName": "vf_for_bdd", + "vendorRelease": "vf_for_bdd", + "componentInstances": [], + "inputs": [{ + "uniqueId": "testInputForBDD", + "type": "org.openecomp.datatypes.Naming", + "required": false, + "definition": false, + "defaultValue": null, + "description": null, + "schema": null, + "password": false, + "name": "abcdef", + "value": null, + "label": null, + "hidden": false, + "immutable": false, + "inputPath": null, + "status": null, + "inputId": null, + "instanceUniqueId": null, + "propertyId": null, + "annotations": null, + "parentUniqueId": "abcd", + "getInputValues": null, + "constraints": null, + "inputs": null, + "properties": null, + "getInputProperty": false, + "schemaType": null, + "schemaProperty": null, + "version": null, + "ownerId": null, + "empty": false + }], + "properties": [], + "attributes": [], + "groups": [], + "resourceType": "VF" +}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/resources/json/interfaceOperation/createInterfaceOperations.json b/cucumber-js-test-apis-ci/resources/json/interfaceOperation/createInterfaceOperations.json new file mode 100644 index 0000000000..ee38f17974 --- /dev/null +++ b/cucumber-js-test-apis-ci/resources/json/interfaceOperation/createInterfaceOperations.json @@ -0,0 +1,31 @@ +{ + "interfaces": { + "interface1": { + "type": "interface1", + "operations": { + "delete": { + "name": "delete", + "description": "description", + "inputs": { + "listToscaDataDefinition": [{ + "name": "inp1", + "type": "string", + "inputId": "c4c6e35f-37d1-4fd5-943c-51257386a86c.nf_naming.instance_name", + "required": true + }] + }, + "outputs": { + "listToscaDataDefinition": [{ + "type": "string", + "required": true, + "name": "op1" + }] + }, + "workflowAssociationType": "NONE", + "workflowId": null, + "workflowVersionId": null + } + } + } + } +}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/resources/json/interfaceOperation/updateInterfaceOperation.json b/cucumber-js-test-apis-ci/resources/json/interfaceOperation/updateInterfaceOperation.json new file mode 100644 index 0000000000..8821e7f837 --- /dev/null +++ b/cucumber-js-test-apis-ci/resources/json/interfaceOperation/updateInterfaceOperation.json @@ -0,0 +1,34 @@ +{ + "interfaces": { + "interface1": { + "type": "interface1", + "operations": { + "delete" : { + "name": "sshGV", + "description": "sshGV updated description" , + "inputs": { + "listToscaDataDefinition": [ + { + "name": "inputId_up", + "type": "string", + "inputId": "c4c6e35f-37d1-4fd5-943c-51257386a86c.nf_naming.instance_name", + "required": true + } + ] + }, + "outputs": { + "listToscaDataDefinition": [{ + "name": "outUp_up", + "type": "string", + "required": true + }] + }, + "uniqueId": "3f6b7144-2dec-48e2-80cb-c67e8bc1d7d2", + "workflowAssociationType": "NONE", + "workflowId": null, + "workflowVersionId": null + } + } + } + } +}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/resources/json/operation/createOperation-with-workflow.json b/cucumber-js-test-apis-ci/resources/json/operation/createOperation-with-workflow.json deleted file mode 100644 index e9693adf2a..0000000000 --- a/cucumber-js-test-apis-ci/resources/json/operation/createOperation-with-workflow.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "interfaceOperations": { - "operation": { - "description": "abcd description", - "inputParams": { - "listToscaDataDefinition": [ - { - "name": "inp1", - "type": "string", - "property": "97477d27-8fe2-45a1-83cb-83368ef2a402.nf_naming_code", - "mandatory": true - } - ] - }, - "outputParams": { - "listToscaDataDefinition": [ - { - "name": "op", - "mandatory": true, - "type": "String" - } - ] - }, - "operationType": "create", - "workflowAssociationType": "EXISTING", - "workflowId" : "workflowId", - "workflowVersionId" : "workflowVersionId" - } - } -}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/resources/json/operation/createOperation.json b/cucumber-js-test-apis-ci/resources/json/operation/createOperation.json deleted file mode 100644 index 10c34ba8f2..0000000000 --- a/cucumber-js-test-apis-ci/resources/json/operation/createOperation.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "interfaceOperations": { - "operation": { - "description": "abcd description", - "inputParams": { - }, - "outputParams": { - }, - "operationType": "create", - "workflowId" : null, - "workflowVersionId" : null - } - } -}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/resources/json/operation/createOperationWithInputOutput.json b/cucumber-js-test-apis-ci/resources/json/operation/createOperationWithInputOutput.json deleted file mode 100644 index 013d615999..0000000000 --- a/cucumber-js-test-apis-ci/resources/json/operation/createOperationWithInputOutput.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "interfaceOperations": { - "operation": { - "description": "abcd description", - "inputParams": { - "listToscaDataDefinition": [ - { - "name": "inp1", - "type": "string", - "property": "97477d27-8fe2-45a1-83cb-83368ef2a402.nf_naming_code", - "mandatory": true - } - ] - }, - "outputParams": { - "listToscaDataDefinition": [ - { - "name": "op", - "mandatory": true, - "type": "String" - } - ] - }, - "operationType": "create", - "workflowId" : null, - "workflowVersionId" : null - } - } -}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/resources/json/operation/createService.json b/cucumber-js-test-apis-ci/resources/json/operation/createService.json deleted file mode 100644 index e7afe2aa21..0000000000 --- a/cucumber-js-test-apis-ci/resources/json/operation/createService.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "artifacts": { - - }, - "toscaArtifacts": { - - }, - "contactId": "cs0008", - "categories": [ - { - "name": "Network L4+", - "normalizedName": "network l4+", - "uniqueId": "serviceNewCategory.network l4+", - "icons": [ - "network_l_4" - ], - "subcategories": null, - "version": null, - "ownerId": null, - "empty": false, - "type": null - } - ], - "description": "service1 for bdd", - "icon": "defaulticon", - "componentInstancesProperties": { - - }, - "componentInstancesAttributes": { - - }, - "name": "service1", - "tags": [ - "service1" - ], - "capabilities": { - - }, - "requirements": { - - }, - "deploymentArtifacts": { - - }, - "componentType": "SERVICE", - "projectCode": "010203", - "componentInstances": [ - - ], - "properties": [ - - ], - - "inputs": [ - { - "uniqueId": "03eeb10e-cf2a-41b8-9d8e-d2dbd094f9d4.test1_dasddas", - "type": "scalar-unit.size", - "required": false, - "definition": false, - "schema": { - "properties": { - - }, - "property": { - "type": "", - "required": false, - "definition": true, - "password": false, - "hidden": false, - "immutable": false, - "getInputProperty": false, - "empty": false - }, - "empty": false - }, - "password": false, - "name": "test1_dasddas", - "hidden": false, - "immutable": false, - "instanceUniqueId": "03eeb10e-cf2a-41b8-9d8e-d2dbd094f9d4", - "propertyId": "03eeb10e-cf2a-41b8-9d8e-d2dbd094f9d4.dasddas", - "parentUniqueId": "cs0008", - "schemaType": "", - "getInputProperty": false, - "ownerId": "cs0008", - "empty": false - } - ], - - "attributes": [ - - ], - "forwardingPaths": { - - }, - "ecompGeneratedNaming": true, - "serviceApiArtifacts": { - - }, - "instantiationType": "A-la-carte", - "environmentContext": "General_Revenue-Bearing" -}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/resources/json/operation/createVF.json b/cucumber-js-test-apis-ci/resources/json/operation/createVF.json deleted file mode 100644 index 6fe9688caa..0000000000 --- a/cucumber-js-test-apis-ci/resources/json/operation/createVF.json +++ /dev/null @@ -1,101 +0,0 @@ -{ - "artifacts": { - - }, - "toscaArtifacts": { - - }, - "contactId": "cs0008", - "categories": [ - { - "name": "Allotted Resource", - "normalizedName": "allotted resource", - "uniqueId": "resourceNewCategory.allotted resource", - "icons": null, - "subcategories": [ - { - "name": "Tunnel XConnect", - "normalizedName": "tunnel xconnect", - "uniqueId": "resourceNewCategory.allotted resource.tunnel xconnect", - "icons": [ - "tunnel_x_connect" - ], - "groupings": null, - "ownerId": null, - "empty": false - } - ], - "ownerId": null, - "empty": false - } - ], - "description": "sd", - "icon": "defaulticon", - "componentInstancesProperties": { - - }, - "componentInstancesAttributes": { - - }, - "name": "REPLACE", - "tags": [ - "REPLACE" - ], - "capabilities": { - - }, - "requirements": { - - }, - "deploymentArtifacts": { - - }, - "componentType": "RESOURCE", - "vendorName": "vendor", - "vendorRelease": "vendor release", - "componentInstances": [ - - ], - "inputs": [{ - "uniqueId": "abcdef", - "type": "org.openecomp.datatypes.Naming", - "required": false, - "definition": false, - "defaultValue": null, - "description": null, - "schema": null, - "password": false, - "name": "abcdef", - "value": null, - "label": null, - "hidden": false, - "immutable": false, - "inputPath": null, - "status": null, - "inputId": null, - "instanceUniqueId": null, - "propertyId": null, - "annotations": null, - "parentUniqueId": "abcd", - "getInputValues": null, - "constraints": null, - "inputs": null, - "properties": null, - "getInputProperty": false, - "schemaType": null, - "schemaProperty": null, - "version": null, - "ownerId": null, - "empty": false - } ], - "properties": [ - - ], - "attributes": [ - - ], - "groups": [ - - ], - "resourceType": "VF" -}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/resources/json/operation/updateOperation.json b/cucumber-js-test-apis-ci/resources/json/operation/updateOperation.json deleted file mode 100644 index 698d38c612..0000000000 --- a/cucumber-js-test-apis-ci/resources/json/operation/updateOperation.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "interfaceOperations": { - "operation": { - "description": "create operation_Updated", - "inputParams": { - "listToscaDataDefinition": [ - { - "name": "inp1", - "type": "string", - "property": "97477d27-8fe2-45a1-83cb-83368ef2a402.nf_naming_code", - "mandatory": true - } - ] - }, - "outputParams": { - "listToscaDataDefinition": [ - { - "name": "op", - "mandatory": true, - "type": "String" - } - ] - }, - "operationType": "create", - "uniqueId": "REPLACE FROM CONTEXT" - } - } -}
\ No newline at end of file diff --git a/cucumber-js-test-apis-ci/stepDefinitions/InterfaceOperationSteps.js b/cucumber-js-test-apis-ci/stepDefinitions/InterfaceOperationSteps.js index 408db9e9f8..abfad80ae4 100644 --- a/cucumber-js-test-apis-ci/stepDefinitions/InterfaceOperationSteps.js +++ b/cucumber-js-test-apis-ci/stepDefinitions/InterfaceOperationSteps.js @@ -19,10 +19,11 @@ const util = require('./Utils.js'); When('I want to create a VF', function() { - let inputData = util.getJSONFromFile('resources/json/operation/createVF.json'); + let inputData = util.getJSONFromFile('resources/json/createVFWithoutCSAR.json'); - inputData.name = util.random(); - inputData.tags[0] = util.random(); + var resourceName = util.random(); + inputData.name = resourceName; + inputData.tags[0] = resourceName; var type = "resources"; let path = '/catalog/' + type; @@ -32,10 +33,11 @@ When('I want to create a VF', function() { }); When('I want to create a Service', function() { - let inputData = util.getJSONFromFile('resources/json/operation/createService.json'); + let inputData = util.getJSONFromFile('resources/json/createService.json'); - inputData.name = util.random(); - inputData.tags[0] = util.random(); + var serviceName = util.random(); + inputData.name = serviceName; + inputData.tags[0] = serviceName; var type = "services"; let path = '/catalog/' + type; @@ -54,47 +56,57 @@ function makeType() { return text; } -When('I want to create an Operation with input output', function() { +When('I want to create an Operation', function() { let path = '/catalog/' + this.context.component.type + '/' + this.context.component.uniqueId + '/interfaceOperations'; - let inputData = util.getJSONFromFile('resources/json/operation/createOperationWithInputOutput.json'); - - inputData.interfaceOperations.operation.inputParams.listToscaDataDefinition[0].name = util.random(); - inputData.interfaceOperations.operation.inputParams.listToscaDataDefinition[0].property = this.context.component.id; - inputData.interfaceOperations.operation.outputParams.listToscaDataDefinition[0].name = util.random(); - inputData.interfaceOperations.operation.operationType = makeType(); - inputData.interfaceOperations.operation.description = makeType(); + let inputData = util.getJSONFromFile('resources/json/interfaceoperation/createInterfaceOperations.json'); + var operationName = makeType(); + var interfaceType = makeType(); + inputData.interfaces.interface1.type = interfaceType; + inputData.interfaces.interface1.operations.delete.name = operationName; + inputData.interfaces.interface1.operations.delete.inputs.listToscaDataDefinition[0].name = util.random(); + inputData.interfaces.interface1.operations.delete.inputs.listToscaDataDefinition[0].inputId = this.context.component.id; + inputData.interfaces.interface1.operations.delete.outputs.listToscaDataDefinition[0].name = util.random(); + inputData.interfaces.interface1.operations.delete.description = operationName + " description"; return util.request(this.context, 'POST', path, inputData, false, 'catalog').then(result => { - this.context.operation = {uniqueId : result.data.uniqueId, operationType : result.data.operationType}; + {intOperations = result.data.interfaces[0].operations}; + this.context.interface = { interfaceUniqueId : result.data.interfaces[0].uniqueId, + interfaceType : result.data.interfaces[0].type, + operationUniqueId : Object.keys(intOperations)[0] + }; }); }); -When('I want to create an Operation', function() { - let path = '/catalog/' + this.context.component.type + '/' + this.context.component.uniqueId + '/interfaceOperations'; - let inputData = util.getJSONFromFile('resources/json/operation/createOperation.json'); - inputData.interfaceOperations.operation.operationType = makeType(); - inputData.interfaceOperations.operation.description = makeType(); +When('I want to update an Operation', function () { + let inputData = util.getJSONFromFile('resources/json/interfaceoperation/updateInterfaceOperation.json'); + let path = '/catalog/'+ this.context.component.type + '/'+ this.context.component.uniqueId +'/interfaceOperations'; + inputData.interfaces.interface1.operations.delete.uniqueId = this.context.interface.operationUniqueId; + inputData.interfaces.interface1.type=this.context.interface.interfaceType; + inputData.interfaces.interface1.operations.delete.inputs.listToscaDataDefinition[0].name = util.random(); + inputData.interfaces.interface1.operations.delete.inputs.listToscaDataDefinition[0].inputId = this.context.component.id; + inputData.interfaces.interface1.operations.delete.outputs.listToscaDataDefinition[0].name = util.random(); - return util.request(this.context, 'POST', path, inputData, false, 'catalog').then(result => { - this.context.operation = {uniqueId : result.data.uniqueId, operationType : result.data.operationType}; + return util.request(this.context, 'PUT', path, inputData, false, 'catalog').then((result)=> { + {intOperations = result.data.interfaces[0].operations}; + this.context.interface = { interfaceUniqueId : result.data.interfaces[0].uniqueId, + interfaceType : result.data.interfaces[0].type, + operationUniqueId : Object.keys(intOperations)[0] + }; }); }); -When('I want to create an Operation with workflow', function() { - let path = '/catalog/' + this.context.component.type + '/' + this.context.component.uniqueId + '/interfaceOperations'; - let inputData = util.getJSONFromFile('resources/json/operation/createOperation-with-workflow.json'); +When('I want to get an Operation by Id', function () { + let path = '/catalog/'+ this.context.component.type + '/' + this.context.component.uniqueId + '/interfaces/' + + this.context.interface.interfaceUniqueId + '/operations/' +this.context.interface.operationUniqueId ; + return util.request(this.context, 'GET', path, null, false, 'catalog').then((result)=> { - inputData.interfaceOperations.operation.inputParams.listToscaDataDefinition[0].name = util.random(); - inputData.interfaceOperations.operation.inputParams.listToscaDataDefinition[0].property = this.context.component.id; - inputData.interfaceOperations.operation.outputParams.listToscaDataDefinition[0].name = util.random(); - inputData.interfaceOperations.operation.operationType = makeType(); - inputData.interfaceOperations.operation.description = makeType(); - inputData.interfaceOperations.operation.workflowId = makeType(); - inputData.interfaceOperations.operation.workflowVersionId = makeType(); + {intOperations = result.data.interfaces[0].operations}; + this.context.interface = { interfaceUniqueId : result.data.interfaces[0].uniqueId, + interfaceType : result.data.interfaces[0].type, + operationUniqueId : Object.keys(intOperations)[0] + }; + }); - return util.request(this.context, 'POST', path, inputData, false, 'catalog').then(result => { - this.context.operation = {uniqueId : result.data.uniqueId, operationType : result.data.operationType}; -}); }); When('I want to list Operations', function () { @@ -103,29 +115,10 @@ When('I want to list Operations', function () { }); }); -When('I want to get an Operation by Id', function () { - let path = '/catalog/'+ this.context.component.type + '/' + this.context.component.uniqueId + '/interfaceOperations/' + this.context.operation.uniqueId; - return util.request(this.context, 'GET', path, null, false, 'catalog').then((result)=> { - this.context.operation = {uniqueId : result.data.uniqueId, operationType : result.data.operationType}; -}); -}); - -When('I want to update an Operation', function () { - let inputData = util.getJSONFromFile('resources/json/operation/updateOperation.json'); - let path = '/catalog/'+ this.context.component.type + '/'+ this.context.component.uniqueId +'/interfaceOperations'; - inputData.interfaceOperations.operation.uniqueId = this.context.operation.uniqueId; - inputData.interfaceOperations.operation.operationType = this.context.operation.operationType; - inputData.interfaceOperations.operation.inputParams.listToscaDataDefinition[0].name = util.random(); - inputData.interfaceOperations.operation.inputParams.listToscaDataDefinition[0].property = this.context.component.id; - inputData.interfaceOperations.operation.outputParams.listToscaDataDefinition[0].name = util.random(); - return util.request(this.context, 'PUT', path, inputData, false, 'catalog').then((result)=> { - this.context.operation = {uniqueId : result.data.uniqueId, operationType : result.data.operationType}; -}); -}); - When('I want to delete an Operation', function() { - let path = '/catalog/'+ this.context.component.type + '/'+ this.context.component.uniqueId +'/interfaceOperations/' + this.context.operation.uniqueId; + let path = '/catalog/'+ this.context.component.type + '/'+ this.context.component.uniqueId +'/interfaces/' + + this.context.interface.interfaceUniqueId + '/operations/' +this.context.interface.operationUniqueId ; return util.request(this.context, 'DELETE', path, null, false, 'catalog'); }); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java index 26b6b6d573..d3b717e514 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java @@ -395,4 +395,10 @@ public interface Urls { // Interface Lifecycle Types final String GET_All_INTERFACE_LIFECYCLE_TYPES = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/interfaceLifecycleTypes"; + + // Interface Operation + final String ADD_INTERFACE_OPERATIONS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/interfaceOperations"; + final String UPDATE_INTERFACE_OPERATIONS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/interfaceOperations"; + final String GET_INTERFACE_OPERATIONS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/interfaces/%s/operations/%s"; + final String DELETE_INTERFACE_OPERATIONS = SDC_HTTP_METHOD + "://%s:%s/sdc2/rest/v1/catalog/%s/%s/interfaces/%s/operations/%s"; } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/interfaceoperation/InterfaceOperationsTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/interfaceoperation/InterfaceOperationsTest.java new file mode 100644 index 0000000000..8b2343c6c9 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/interfaceoperation/InterfaceOperationsTest.java @@ -0,0 +1,264 @@ +package org.openecomp.sdc.ci.tests.execute.interfaceoperation; + +import static org.testng.AssertJUnit.fail; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import fj.data.Either; +import java.util.HashMap; +import java.util.Map; +import org.junit.Rule; +import org.junit.rules.TestName; +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.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.InterfaceDefinition; +import org.openecomp.sdc.be.model.Operation; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.InterfaceOperationsRestUtils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class InterfaceOperationsTest extends ComponentBaseTest { + + @Rule + private static final TestName name = new TestName(); + private static final String INTERFACES = "interfaces"; + private static final String TOSCA_PRESENTATION = "toscaPresentation"; + private static final User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + private static Service service; + private static Resource resource; + private String resourceInterfaceUniqueId; + private String resourceOperationUniqueId; + private String serviceInterfaceUniqueId; + private String serviceOperationUniqueId; + + public InterfaceOperationsTest() { + super(name, InterfaceOperationsTest.class.getName()); + } + + @BeforeClass + public static void init() throws Exception { + // Create default service + Either<Service, RestResponse> createDefaultServiceEither = + AtomicOperationUtils.createDefaultService(UserRoleEnum.DESIGNER, true); + if (createDefaultServiceEither.isRight()) { + fail("Error creating default service"); + } + service = createDefaultServiceEither.left().value(); + + // Create default resource + Either<Resource, RestResponse> createDefaultResourceEither = + AtomicOperationUtils.createResourceByType(ResourceTypeEnum.VF, UserRoleEnum.DESIGNER, true); + if (createDefaultResourceEither.isRight()) { + fail("Error creating default resource"); + } + resource = createDefaultResourceEither.left().value(); + } + + private Map<String, Object> buildInterfaceDefinitionForResource() { + Operation operation = new Operation(); + operation.setName("TestOperationOnResource"); + operation.setWorkflowId("WorkflowId"); + operation.setWorkflowVersionId("workflowVersionId"); + operation.setWorkflowAssociationType("NONE"); + PropertyDefinition property = + resource.getInputs().stream().filter(a -> a.getName().equalsIgnoreCase("nf_naming")).findFirst() + .orElse(new InputDefinition()); + ListDataDefinition<OperationInputDefinition> operationInputDefinitionList = new ListDataDefinition<>(); + operationInputDefinitionList.add(createOperationInputDefinition("TestInput1", property.getUniqueId())); + operation.setInputs(operationInputDefinitionList); + ListDataDefinition<OperationOutputDefinition> operationOutputDefinitionList = new ListDataDefinition<>(); + operationOutputDefinitionList.add(createOperationOutputDefinition("TestOutput1")); + operation.setOutputs(operationOutputDefinitionList); + return buildInterfaceDefinitionMap(operation, "TestInterface", resourceInterfaceUniqueId, resourceOperationUniqueId); + } + + private Map<String, Object> buildInterfaceDefinitionOfGlobalTypeForResource() { + Operation operation = new Operation(); + operation.setName("create"); + operation.setWorkflowId("WorkflowId"); + operation.setWorkflowVersionId("workflowVersionId"); + operation.setWorkflowAssociationType("NONE"); + PropertyDefinition property = + resource.getInputs().stream().filter(a -> a.getName().equalsIgnoreCase("nf_naming")).findFirst() + .orElse(new InputDefinition()); + ListDataDefinition<OperationInputDefinition> operationInputDefinitionList = new ListDataDefinition<>(); + operationInputDefinitionList.add(createOperationInputDefinition("TestInput1", property.getUniqueId())); + operation.setInputs(operationInputDefinitionList); + ListDataDefinition<OperationOutputDefinition> operationOutputDefinitionList = new ListDataDefinition<>(); + operationOutputDefinitionList.add(createOperationOutputDefinition("TestOutput1")); + operation.setOutputs(operationOutputDefinitionList); + return buildInterfaceDefinitionMap(operation,"tosca.interfaces.node.lifecycle.Standard", resourceInterfaceUniqueId, resourceOperationUniqueId); + } + + private OperationInputDefinition createOperationInputDefinition(String name, String inputId) { + OperationInputDefinition operationInputDefinition = new OperationInputDefinition(); + operationInputDefinition.setName(name); + operationInputDefinition.setInputId(inputId); + operationInputDefinition.setRequired(true); + operationInputDefinition.setType("string"); + return operationInputDefinition; + } + + private OperationOutputDefinition createOperationOutputDefinition(String name) { + OperationOutputDefinition operationOutputDefinition = new OperationOutputDefinition(); + operationOutputDefinition.setName(name); + operationOutputDefinition.setRequired(true); + operationOutputDefinition.setType("string"); + return operationOutputDefinition; + } + + private Map<String, Object> buildInterfaceDefinitionMap(Operation operation, String interfaceType, String interfaceId, + String operationId) { + if (operationId != null) { + operation.setUniqueId(operationId); + } + Map<String, Operation> operationMap = new HashMap<>(); + operationMap.put(operation.getName(), operation); + + InterfaceDefinition interfaceDefinition = new InterfaceDefinition(); + interfaceDefinition.setType(interfaceType); + interfaceDefinition.setOperationsMap(operationMap); + if (interfaceId != null) { + interfaceDefinition.setUniqueId(interfaceId); + } + interfaceDefinition.setOperationsMap(operationMap); + + Map<String, Object> interfaceDefAsMap = getObjectAsMap(interfaceDefinition); + Map<String, Object> interfaceMap = new HashMap<>(); + interfaceMap.put(interfaceDefinition.getType(), interfaceDefAsMap); + Map<String, Object> outerMap = new HashMap<>(); + outerMap.put(INTERFACES, interfaceMap); + return outerMap; + } + + private static Map<String, Object> getObjectAsMap(Object obj) { + ObjectMapper objectMapper = new ObjectMapper(); + if (obj instanceof InterfaceDefinition) { + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + } + Map<String, Object> objectAsMap = + obj instanceof Map ? (Map<String, Object>) obj : objectMapper.convertValue(obj, Map.class); + objectAsMap.remove(TOSCA_PRESENTATION); + return objectAsMap; + } + + private Map<String, Object> buildInterfaceDefinitionForService() { + Operation operation = new Operation(); + operation.setName("TestOperationOnService"); + operation.setWorkflowId("WorkflowId"); + operation.setWorkflowVersionId("workflowVersionId"); + operation.setWorkflowAssociationType("NONE"); + return buildInterfaceDefinitionMap(operation,"TestInterface", serviceInterfaceUniqueId, serviceOperationUniqueId); + } + + @Test + public void addInterfaceOperationsOnResource() throws Exception { + RestResponse restResponse = InterfaceOperationsRestUtils + .addInterfaceOperations(resource, buildInterfaceDefinitionForResource(), + user); + logger.info("addInterfaceOperationsOnResource Response Code:" + restResponse.getErrorCode()); + Assert.assertEquals((int) restResponse.getErrorCode(), BaseRestUtils.STATUS_CODE_SUCCESS); + String interfaceDefinitionStr = ResponseParser.getListFromJson(restResponse, INTERFACES).get(0).toString(); + InterfaceDefinition interfaceDefinition = + ResponseParser.convertInterfaceDefinitionResponseToJavaObject(interfaceDefinitionStr); + resourceInterfaceUniqueId = interfaceDefinition.getUniqueId(); + resourceOperationUniqueId = interfaceDefinition.getOperationsMap().keySet().stream().findFirst().orElse(null); + } + + @Test(dependsOnMethods = "addInterfaceOperationsOnResource") + public void getInterfaceOperationsFromResource() throws Exception { + RestResponse restResponse = InterfaceOperationsRestUtils + .getInterfaceOperations(resource, resourceInterfaceUniqueId, + resourceOperationUniqueId, user); + logger.info("getInterfaceOperationsFromResource Response Code:" + restResponse.getErrorCode()); + Assert.assertEquals((int) restResponse.getErrorCode(), BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test(dependsOnMethods = "getInterfaceOperationsFromResource") + public void updateInterfaceOperationsOnResource() throws Exception { + RestResponse restResponse = InterfaceOperationsRestUtils + .updateInterfaceOperations(resource, buildInterfaceDefinitionForResource(), + user); + logger.info("updateInterfaceOperationsOnResource Response Code:" + restResponse.getErrorCode()); + Assert.assertEquals((int) restResponse.getErrorCode(), BaseRestUtils.STATUS_CODE_SUCCESS); + } + + /*@Test(dependsOnMethods = "updateInterfaceOperationsOnResource") + public void deleteInterfaceOperationsFromResource() throws Exception { + RestResponse restResponse = InterfaceOperationsRestUtils + .deleteInterfaceOperations(resource, resourceInterfaceUniqueId, + resourceOperationUniqueId, user); + logger.info("deleteInterfaceOperationsFromResource Response Code:" + restResponse.getErrorCode()); + Assert.assertEquals((int) restResponse.getErrorCode(), BaseRestUtils.STATUS_CODE_SUCCESS); + }*/ + + @Test + public void addInterfaceOperationsOnService() throws Exception { + RestResponse restResponse = InterfaceOperationsRestUtils + .addInterfaceOperations(service, buildInterfaceDefinitionForService(), + user); + logger.info("addInterfaceOperationsOnService Response Code:" + restResponse.getErrorCode()); + Assert.assertEquals((int) restResponse.getErrorCode(), BaseRestUtils.STATUS_CODE_SUCCESS); + String interfaceDefinitionStr = ResponseParser.getListFromJson(restResponse, INTERFACES).get(0).toString(); + InterfaceDefinition interfaceDefinition = + ResponseParser.convertInterfaceDefinitionResponseToJavaObject(interfaceDefinitionStr); + serviceInterfaceUniqueId = interfaceDefinition.getUniqueId(); + serviceOperationUniqueId = interfaceDefinition.getOperationsMap().keySet().stream().findFirst().orElse(null); + } + + @Test(dependsOnMethods = "addInterfaceOperationsOnService") + public void getInterfaceOperationsFromService() throws Exception { + RestResponse restResponse = InterfaceOperationsRestUtils + .getInterfaceOperations(service, serviceInterfaceUniqueId, + serviceOperationUniqueId, user); + logger.info("getInterfaceOperationsFromService Response Code:" + restResponse.getErrorCode()); + Assert.assertEquals((int) restResponse.getErrorCode(), BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test(dependsOnMethods = "getInterfaceOperationsFromService") + public void updateInterfaceOperationsOnService() throws Exception { + RestResponse restResponse = InterfaceOperationsRestUtils + .updateInterfaceOperations(service, buildInterfaceDefinitionForService(), + user); + logger.info("updateInterfaceOperations Response Code:" + restResponse.getErrorCode()); + Assert.assertEquals((int) restResponse.getErrorCode(), BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test(dependsOnMethods = "updateInterfaceOperationsOnService") + public void deleteInterfaceOperationsFromService() throws Exception { + RestResponse restResponse = InterfaceOperationsRestUtils + .deleteInterfaceOperations(service, serviceInterfaceUniqueId, + serviceOperationUniqueId, user); + logger.info("deleteInterfaceOperations Response Code:" + restResponse.getErrorCode()); + Assert.assertEquals((int) restResponse.getErrorCode(), BaseRestUtils.STATUS_CODE_SUCCESS); + } + + @Test + public void addInterfaceOperationsOfGlobalTypeOnResource() throws Exception { + RestResponse restResponse = InterfaceOperationsRestUtils + .addInterfaceOperations(resource, buildInterfaceDefinitionOfGlobalTypeForResource(), + user); + logger.info("addInterfaceOperationsOnResource Response Code:" + restResponse.getErrorCode()); + Assert.assertEquals((int) restResponse.getErrorCode(), BaseRestUtils.STATUS_CODE_SUCCESS); + String interfaceDefinitionStr = ResponseParser.getListFromJson(restResponse, INTERFACES).get(0).toString(); + InterfaceDefinition interfaceDefinition = + ResponseParser.convertInterfaceDefinitionResponseToJavaObject(interfaceDefinitionStr); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InterfaceOperationsRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InterfaceOperationsRestUtils.java new file mode 100644 index 0000000000..c3486cdad1 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/InterfaceOperationsRestUtils.java @@ -0,0 +1,59 @@ +package org.openecomp.sdc.ci.tests.utils.rest; + +import com.google.gson.Gson; +import java.io.IOException; +import java.util.Map; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class InterfaceOperationsRestUtils extends BaseRestUtils { + + @SuppressWarnings("unused") + private static Logger logger = LoggerFactory.getLogger(InterfaceOperationsRestUtils.class.getName()); + + public static RestResponse addInterfaceOperations(Component component, Map<String, Object> interfaceDefinitionMap, + User user) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.ADD_INTERFACE_OPERATIONS, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId()); + String jsonBody = new Gson().toJson(interfaceDefinitionMap); + return sendPost(url, jsonBody, user.getUserId(), acceptHeaderData); + } + + public static RestResponse updateInterfaceOperations(Component component, + Map<String, Object> interfaceDefinitionMap, User user) throws IOException { + Config config = Utils.getConfig(); + String url = + String.format(Urls.UPDATE_INTERFACE_OPERATIONS, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId()); + String jsonBody = new Gson().toJson(interfaceDefinitionMap); + return sendPut(url, jsonBody, user.getUserId(), acceptHeaderData); + } + + public static RestResponse getInterfaceOperations(Component component, String interfaceId, String operationIds, + User user) throws IOException { + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_INTERFACE_OPERATIONS, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), interfaceId, + operationIds); + return sendGet(url, user.getUserId()); + } + + public static RestResponse deleteInterfaceOperations(Component component, String interfaceId, String operationIds, + User user) throws IOException { + Config config = Utils.getConfig(); + String url = + String.format(Urls.DELETE_INTERFACE_OPERATIONS, config.getCatalogBeHost(), config.getCatalogBePort(), + ComponentTypeEnum.findParamByType(component.getComponentType()), component.getUniqueId(), + interfaceId, operationIds); + return sendDelete(url, user.getUserId()); + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java index ec2121475e..30e54d3914 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResponseParser.java @@ -680,4 +680,18 @@ public class ResponseParser { return vfModulesMap; } + public static InterfaceDefinition convertInterfaceDefinitionResponseToJavaObject(String response) { + ObjectMapper mapper = new ObjectMapper(); + InterfaceDefinition interfaceDefinition = null; + try { + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + interfaceDefinition = mapper.readValue(response, InterfaceDefinition.class); + logger.debug(interfaceDefinition.toString()); + } + catch (IOException e) { + logger.debug(e); + } + return interfaceDefinition; + } + } diff --git a/test-apis-ci/src/main/resources/ci/testSuites/resource.xml b/test-apis-ci/src/main/resources/ci/testSuites/resource.xml index 803fb01e70..05080b25ac 100644 --- a/test-apis-ci/src/main/resources/ci/testSuites/resource.xml +++ b/test-apis-ci/src/main/resources/ci/testSuites/resource.xml @@ -354,6 +354,15 @@ <include name="undoCheckOutProductByPm"/> </methods> </class> + <class name="org.openecomp.sdc.ci.tests.execute.interfaceoperation.InterfaceOperationsTest"> + <methods> + <include name="addInterfaceOperationsOfGlobalTypeOnResource"/> + <include name="addInterfaceOperationsOnResource"/> + <include name="getInterfaceOperationsFromResource"/> + <include name="updateInterfaceOperationsOnResource"/> + <include name="deleteInterfaceOperationsFromResource"/> + </methods> + </class> <!-- Product tests end--> </classes> </test> <!-- Test --> diff --git a/test-apis-ci/src/main/resources/ci/testSuites/service.xml b/test-apis-ci/src/main/resources/ci/testSuites/service.xml index 18d5630c4e..5c64fb49cb 100644 --- a/test-apis-ci/src/main/resources/ci/testSuites/service.xml +++ b/test-apis-ci/src/main/resources/ci/testSuites/service.xml @@ -10,6 +10,14 @@ <class name="org.openecomp.sdc.ci.tests.execute.service.ServiceComponentInstanceCRUDTest"/> <class name="org.openecomp.sdc.ci.tests.execute.service.UpdateServiceMetadataTest"/> <class name="org.openecomp.sdc.ci.tests.execute.service.GetAllServiceVersions"/> + <class name="org.openecomp.sdc.ci.tests.execute.interfaceoperation.InterfaceOperationsTest"> + <methods> + <include name="addInterfaceOperationsOnService"/> + <include name="getInterfaceOperationsFromService"/> + <include name="updateInterfaceOperationsOnService"/> + <include name="deleteInterfaceOperationsFromService"/> + </methods> + </class> </classes> </test> </suite> <!-- Service --> |