diff options
Diffstat (limited to 'catalog-be/src')
22 files changed, 1171 insertions, 1102 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 ef29b93001..2b3ee0ed2e 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.components.utils.InterfaceOperationUtils; +import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils; 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; @@ -3058,7 +3058,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } } else { return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user, - decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId, + decodedPayload, componentType, auditingAction, operationUuid, artifactData, prevArtifactId, currArtifactId, artifactDefinition); } @@ -3067,7 +3067,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, String interfaceType, + byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId, ArtifactDefinition artifactDefinition) { StorageOperationStatus error; @@ -3110,15 +3110,24 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { } Component storedComponent = componentStorageOperationStatusEither.left().value(); - Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils - .getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType); - if(!optionalInterface.isPresent()) { + 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()) { log.debug("Failed to get resource interface for resource Id {}", parentId); - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType)); + 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); } //fetch the operation from storage - InterfaceDefinition gotInterface = optionalInterface.get(); + InterfaceDefinition gotInterface = interfaceDefinition.get(); Map<String, Operation> operationsMap = gotInterface.getOperationsMap(); Optional<Operation> optionalOperation = operationsMap.values() .stream() @@ -3143,8 +3152,8 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { implementationArtifact.setEsId(artifactInfo.getEsId()); operation.setImplementation(implementationArtifact); gotInterface.setOperationsMap(operationsMap); - Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither = - interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface)); + Either<InterfaceDefinition, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither = + interfaceOperation.updateInterface(storedComponent.getUniqueId(), gotInterface); if (interfaceDefinitionStorageOperationStatusEither.isRight()){ StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value(); ActionStatus actionStatus = @@ -5018,13 +5027,13 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { * @param componentType * @param componentUuid * @param artifactUUID - * @param operation + * @param operation TODO * @return */ public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID( String data, HttpServletRequest request, ComponentTypeEnum componentType, - String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID, - ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) { + String componentUuid, String artifactUUID, String operationUUID, + ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); Either<ArtifactDefinition, ResponseFormat> updateArtifactResult; Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null; @@ -5058,7 +5067,7 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { resourceCommonInfo.setResourceName(componentName); } if (errorWrapper.isEmpty()) { - Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId, interfaceUUID); + Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId); if (interfaceName.isRight()) { errorWrapper.setInnerElement(interfaceName.right().value()); } @@ -5085,21 +5094,19 @@ public class ArtifactsBusinessLogic extends BaseBusinessLogic { return updateArtifactResult; } - private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) { - Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId); + private Either<String, ResponseFormat> fetchInterfaceName(String componentId) { + 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(); - 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()); + return Either.left(InterfaceUtils.createInterfaceToscaResourceName( + storedComponent.getName())); } 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 8ee1864862..02e64334f9 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,7 +128,10 @@ public abstract class BaseBusinessLogic { protected InterfaceOperation interfaceOperation; @Autowired - protected InterfaceLifecycleOperation interfaceLifecycleTypeOperation; + protected InterfaceOperationBusinessLogic interfaceOperationBusinessLogic; + + @Autowired + protected InterfaceLifecycleOperation interfaceLifecycleOperation; @javax.annotation.Resource private UserValidations userValidations; @@ -164,6 +167,18 @@ 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 2bb53d01e7..a0efddbdda 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,28 +18,15 @@ 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.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.ComponentTypeEnum; 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; @@ -60,6 +47,7 @@ import java.util.stream.Collectors; 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 DELETE_INTERFACE_OPERATION = "deleteInterfaceOperation"; private static final String GET_INTERFACE_OPERATION = "getInterfaceOperation"; @@ -67,19 +55,19 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { private static final String UPDATE_INTERFACE_OPERATION = "updateInterfaceOperation"; @Autowired - private ArtifactCassandraDao artifactCassandraDao; - - @Autowired private 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 void setInterfaceOperationValidation(InterfaceOperationValidation interfaceOperationValidation) { + this.interfaceOperationValidation = interfaceOperationValidation; + } + 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()){ 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); if (lockResult.isRight()) { @@ -87,53 +75,26 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } try { - Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils - .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceId); - if(!optionalInterface.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId)); + 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 = 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())); - } + InterfaceDefinition interfaceDefinition = getInterfaceEither.left().value(); - 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); - } - - 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, ResponseFormat> getOperationEither = getOperationFromInterfaceDef(storedComponent, interfaceDefinition, interfaceOperationToDelete); + if (getOperationEither.isRight()){ + return Either.right(getOperationEither.right().value()); } - 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()))); - } + 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()))); } titanDao.commit(); - interfaceDefinition.getOperations().putAll(operationsCollection); - interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToDelete.contains(key))); - return Either.left(Arrays.asList(interfaceDefinition)); + return Either.left(deleteEither.left().value()); } catch (Exception e){ LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "delete", e); @@ -147,14 +108,13 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } } - public Either<List<InterfaceDefinition>, ResponseFormat> getInterfaceOperation(String componentId, String interfaceId, List<String> operationsToGet, User user, boolean lock) { - validateUserExists(user.getUserId(), GET_INTERFACE_OPERATION, true); - + public Either<Operation, ResponseFormat> getInterfaceOperation(String componentId, String interfaceOperationToGet, User user, boolean lock) { Either<org.openecomp.sdc.be.model.Component, ResponseFormat> componentEither = getComponentDetails(componentId); 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); if (lockResult.isRight()) { @@ -162,24 +122,20 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } try { - Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils - .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceId); - if(!optionalInterface.isPresent()) { - return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceId)); + 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 = optionalInterface.get(); + InterfaceDefinition interfaceDefinition = getInterfaceEither.left().value(); - 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())); - } + Either<Operation, ResponseFormat> getOperationEither = getOperationFromInterfaceDef(storedComponent, interfaceDefinition, interfaceOperationToGet); + if (getOperationEither.isRight()){ + return Either.right(getOperationEither.right().value()); } titanDao.commit(); - interfaceDefinition.getOperations().keySet().removeIf(key -> !(operationsToGet.contains(key))); - return Either.left(Arrays.asList(interfaceDefinition)); + return Either.left(getOperationEither.left().value()); } catch (Exception e){ LOGGER.error(EXCEPTION_OCCURRED_DURING_INTERFACE_OPERATION, "get", e); @@ -193,110 +149,78 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { } } - 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); + 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> updateInterfaceOperation(String componentId, List<InterfaceDefinition> interfaceDefinitions, User user, boolean lock) { - return createOrUpdateInterfaceOperation(componentId, interfaceDefinitions, user, true, UPDATE_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<Map<String, InterfaceDefinition>, ResponseFormat> getAllInterfaceLifecycleTypes() { - - Either<Map<String, InterfaceDefinition>, StorageOperationStatus> interfaceLifecycleTypes = interfaceLifecycleTypeOperation.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))))); - - return Either.left(interfaceLifecycleTypes.left().value()); + 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()){ 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 { - 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()); - } - - Map<String, Operation> operationsToAddOrUpdate = inputInterfaceDefinition.getOperationsMap(); - operationsCollection.putAll(operationsToAddOrUpdate); - inputInterfaceDefinition.getOperations().clear(); + 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(); - Either<InterfaceDefinition, ResponseFormat> getInterfaceEither = getOrCreateInterfaceDefinition(storedComponent, inputInterfaceDefinition, optionalInterface.orElse(null)); - if (getInterfaceEither.isRight()) { - return Either.right(getInterfaceEither.right().value()); - } - 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); - } + 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()); } - interfacesCollection.add(interfaceDef); + updateExistingOperation(operation, getOperationEither.left().value().getImplementation().getArtifactUUID()); + result = interfaceOperation.updateInterfaceOperation(componentId, interfaceDefinition, operation); } - Either<List<InterfaceDefinition>, StorageOperationStatus> addCreateOperationEither = interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), interfacesCollection); - if (addCreateOperationEither.isRight()) { + if (result.isRight()) { titanDao.rollback(); - return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(addCreateOperationEither.right().value(), storedComponent.getComponentType()))); + 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()))); } titanDao.commit(); - 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); + return Either.left(result.left().value()); } catch (Exception e) { titanDao.rollback(); @@ -313,69 +237,104 @@ public class InterfaceOperationBusinessLogic extends BaseBusinessLogic { 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()))); + 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()); } - 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()); - } + 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())); } - return Either.left(true); + return Either.left(operationMap.get().getValue()); } - 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(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(interfaceCreateEither.right().value(), component.getComponentType()))); - } - return Either.left(interfaceCreateEither.left().value().get(0)); - } - } - - private void addOperationToInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation){ + 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); - interfaceOperation.setUniqueId(UUID.randomUUID().toString()); - interfaceOperation.setImplementation(artifactDefinition); - interfaceDefinition.getOperations().put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation)); + operation.setUniqueId(UUID.randomUUID().toString()); + operation.setImplementation(artifactDefinition); } - private void updateOperationOnInterface(InterfaceDefinition interfaceDefinition, Operation interfaceOperation, String artifactUUID){ + 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); - interfaceOperation.setImplementation(artifactDefinition); - interfaceDefinition.getOperations().put(interfaceOperation.getUniqueId(), new OperationDataDefinition(interfaceOperation)); + operation.setImplementation(artifactDefinition); } - 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<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()); + titanDao.rollback(); + return Either.right(lockResult.right().value()); + } + } + 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 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); + } + + public Either<Map<String, InterfaceDefinition>, ResponseFormat> getAllInterfaceLifecycleTypes() { + + 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))))); + + return Either.left(interfaceLifecycleTypes.left().value()); + } } 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 4e842928ef..7917a0aa5d 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,6 +3984,14 @@ 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 8d4f896d47..e85afdc48f 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,7 +518,11 @@ 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 deleted file mode 100644 index bac23b2133..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtils.java +++ /dev/null @@ -1,54 +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.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 final 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 final 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 final Optional<Map.Entry<String, Operation>> getOperationFromInterfaceDefinition(InterfaceDefinition interfaceDefinition, String operationId) { - if (MapUtils.isEmpty(interfaceDefinition.getOperationsMap())) { - return Optional.empty(); - } - Optional<Map.Entry<String, Operation>> operationMap = interfaceDefinition.getOperationsMap().entrySet().stream().filter(entry -> entry.getValue().getUniqueId().equals(operationId)).findAny(); - if (operationMap.isPresent()) { - return operationMap; - } - return Optional.empty(); - } - -} 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 bfb2429a83..7b650e4fad 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,7 +16,6 @@ package org.openecomp.sdc.be.components.validation; -import fj.data.Either; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -26,11 +25,16 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; -import java.util.stream.Stream; +import java.util.stream.Collectors; + +import fj.data.Either; 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; @@ -44,117 +48,64 @@ import org.springframework.stereotype.Component; 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 Logger LOGGER = LoggerFactory.getLogger(InterfaceOperationValidation.class); 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; - } + Collection<Operation> interfaceOperations, org.openecomp.sdc.be.model.Component component, boolean isUpdate) { - Either<Boolean, ResponseFormat> validateOperationNameUniqueness = validateOperationNameUniquenessInCollection(inputInterfaceDefinition.getOperationsMap().values()); - if(validateOperationNameUniqueness.isRight()){ - return validateOperationNameUniqueness; - } - - for(Operation interfaceOperation : inputInterfaceDefinition.getOperationsMap().values()) { + for(Operation interfaceOperation : interfaceOperations) { Either<Boolean, ResponseFormat> interfaceOperationValidatorResponse = validateInterfaceOperation( - interfaceOperation, storedInterfaceDefinition, component, isUpdate); + interfaceOperation, component, isUpdate); if (interfaceOperationValidatorResponse.isRight()) { return interfaceOperationValidatorResponse; } } - - return Either.left(Boolean.TRUE); - } - - 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); - } - - 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())); - } - - 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().map(operation -> operation)) - .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); } 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); + responseFormatManager, component, isUpdate); if (interfaceOperationTypeResponse.isRight()) { return Either.right(interfaceOperationTypeResponse.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> descriptionResponseEither = isValidDescription(responseFormatManager, + interfaceOperation.getDescription()); + if (descriptionResponseEither.isRight()) { + return Either.right(descriptionResponseEither.right().value()); + } - Either<Boolean, ResponseFormat> inputPropertyExistInComponent = validateInputPropertyExistInComponent(interfaceOperation, - component, responseFormatManager); - if(inputPropertyExistInComponent.isRight()) { - return Either.right(inputPropertyExistInComponent.right().value()); + Either<Boolean, ResponseFormat> inputPropertyExistInComponent = validateInputPropertyExistInComponent(interfaceOperation, + component.getInputs(), responseFormatManager); + if(inputPropertyExistInComponent.isRight()) { + return Either.right(inputPropertyExistInComponent.right().value()); - } } - if(null != interfaceOperation.getOutputs()) { - Either<Boolean, ResponseFormat> outputParametersResponse = validateOutputParameters(interfaceOperation, responseFormatManager); - if (outputParametersResponse.isRight()) { - return Either.right(outputParametersResponse.right().value()); - } + Either<Boolean, ResponseFormat> inputParametersResponse = validateInputParameters(interfaceOperation, + responseFormatManager); + if(inputParametersResponse.isRight()) { + return Either.right(inputParametersResponse.right().value()); + } + + Either<Boolean, ResponseFormat> outputParametersResponse = validateOutputParameters(interfaceOperation, + responseFormatManager); + if(outputParametersResponse.isRight()) { + return Either.right(outputParametersResponse.right().value()); } return Either.left(Boolean.TRUE); } private Either<Boolean, ResponseFormat> isInterfaceOperationTypeValid(Operation interfaceOperation, - ResponseFormatManager responseFormatManager, InterfaceDefinition interfaceDefinition, - boolean isUpdate) { + ResponseFormatManager responseFormatManager, + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { Either<Boolean, ResponseFormat> operationTypeEmptyEither = isOperationTypeEmpty(responseFormatManager, interfaceOperation.getName()); @@ -169,7 +120,7 @@ public class InterfaceOperationValidation { } Either<Boolean, ResponseFormat> operationTypeUniqueResponse = validateOperationTypeUnique(interfaceOperation, - interfaceDefinition, isUpdate ); + component, isUpdate ); if(operationTypeUniqueResponse.isRight()) { return Either.right(operationTypeUniqueResponse.right().value()); } @@ -205,21 +156,42 @@ public class InterfaceOperationValidation { 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); + 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, InterfaceDefinition interfaceDefinition, + Operation interfaceOperation, + org.openecomp.sdc.be.model.Component component, boolean isUpdate) { boolean isOperationTypeUnique = false; - if(interfaceDefinition == null || CollectionUtils.isEmpty(interfaceDefinition.getOperationsMap().values())){ + 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)){ return Either.left(true); } Map<String, String> operationTypes = new HashMap<>(); - interfaceDefinition.getOperationsMap().values().forEach(operationType -> operationTypes.put(operationType.getUniqueId(), operationType.getName())); + allOperations.forEach(operationType -> operationTypes.put(operationType.getUniqueId(), operationType.getName())); if (!operationTypes.values().contains(interfaceOperation.getName())){ isOperationTypeUnique = true; @@ -234,7 +206,6 @@ public class InterfaceOperationValidation { return Either.left(isOperationTypeUnique); } - private Either<Boolean, ResponseFormat> validateInputParameters(Operation interfaceOperation, ResponseFormatManager responseFormatManager) { if (isInputParameterNameEmpty(interfaceOperation)) { @@ -313,15 +284,19 @@ public class InterfaceOperationValidation { } private Either<Boolean, ResponseFormat> validateInputPropertyExistInComponent(Operation operation, - org.openecomp.sdc.be.model.Component component, - ResponseFormatManager responseFormatManager) { + List<InputDefinition> inputs, + ResponseFormatManager responseFormatManager) { + ListDataDefinition<OperationInputDefinition> inputDefinitionListDataDefinition = operation.getInputs(); + if (inputDefinitionListDataDefinition == null) { + return Either.left(Boolean.TRUE); + } + List<OperationInputDefinition> inputListToscaDataDefinition = inputDefinitionListDataDefinition.getListToscaDataDefinition(); - 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(); + 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, component.getComponentType().getValue()); + ResponseFormat inputResponse = responseFormatManager.getResponseFormat(ActionStatus.INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT, missingPropertyName); return Either.right(inputResponse); } } @@ -329,14 +304,14 @@ public class InterfaceOperationValidation { } private boolean validateInputExistsInComponent(OperationInputDefinition input, - List<InputDefinition> inputs) { + 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('.'))))) ; + || ((input.getInputId().contains(".") + && inputs.stream().anyMatch(inp -> inp.getUniqueId().equals( + input.getInputId().substring(0, input.getInputId().lastIndexOf(".")))))) ; } - protected ResponseFormatManager getResponseFormatManager() { + private ResponseFormatManager getResponseFormatManager() { return ResponseFormatManager.getInstance(); } 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 new file mode 100644 index 0000000000..7fbc56a624 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/datamodel/utils/InterfaceUIDataConverter.java @@ -0,0 +1,106 @@ +/* + * 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 31bc165ee0..03c5e0fbf1 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 @@ -98,7 +98,7 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { private static String startLog = "Start handle request of "; @POST - @Path("/{assetType}/{uuid}/interfaces/{interfaceUUID}/operations/{operationUUID}/artifacts/{artifactUUID}") + @Path("/{assetType}/{uuid}/interfaces/{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,7 +127,6 @@ 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) { @@ -155,7 +154,7 @@ public class ArtifactExternalServlet extends AbstractValidationsServlet { ArtifactsBusinessLogic artifactsLogic = getArtifactBL(context); Either<ArtifactDefinition, ResponseFormat> uploadArtifactEither = artifactsLogic .updateArtifactOnInterfaceOperationByResourceUUID(data, request, ComponentTypeEnum - .findByParamName(assetType), uuid, interfaceUUID, operationUUID, artifactUUID, + .findByParamName(assetType), uuid, artifactUUID, operationUUID, 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 af6976d7b3..815f9763f9 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,7 +16,6 @@ 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; @@ -24,11 +23,8 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; +import java.util.Optional; +import java.util.UUID; import javax.inject.Singleton; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -47,9 +43,10 @@ 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.datatypes.enums.JsonPresentationFields; -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.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.ui.model.UiComponentDataTransfer; @@ -59,10 +56,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Loggable(prepend = true, value = Loggable.DEBUG, trim = false) -@Path("/v1/catalog") +@Path("/v1/catalog/{componentType}/{componentId}/interfaceOperations") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) -@Api(value = "Interface Operation Servlet", description = "Interface Operation Servlet") +@Api(value = "Interface Operation", description = "Interface Operation Servlet") @Singleton public class InterfaceOperationServlet extends AbstractValidationsServlet { @@ -71,154 +68,72 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { @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 = Response.class) - @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); - } - - @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 = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Update Interface Operations on Resource"), - @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @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 = 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/{operationIds}") - @ApiOperation(value = "Delete Interface Operations from Resource", httpMethod = "DELETE", notes = "Delete Interface Operations from Resource", response = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Delete Interface Operations 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 = "Comma seperated value of Operation Ids") @PathParam("operationIds") String operationIds, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - return delete(interfaceId, operationIds, resourceId, request, userId); - } - - @GET - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @Path("/resources/{resourceId}/interfaces/{interfaceId}/operations/{operationIds}") - @ApiOperation(value = "Get Interface Operations from Resource", httpMethod = "GET", notes = "GET Interface Operations from Resource", response = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Delete Interface Operations 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 = "Comma seperated value of operationIds") @PathParam("operationIds") String operationIds, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - return get(interfaceId, operationIds, resourceId, request, userId); - } - - @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 = Response.class) - @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); + 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("/services/{serviceId}/interfaceOperations") - @ApiOperation(value = "Update Interface Operations on Service", httpMethod = "PUT", notes = "Update Interface Operations on Service", response = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Update Interface Operations on Service"), - @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @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 = 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); + @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("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationIds}") - @ApiOperation(value = "Delete Interface Operations from Service", httpMethod = "DELETE", notes = "Delete Interface Operations from Service", response = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Delete Interface Operations from Service"), - @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @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 = 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 = "Comma seperated value of Operation Ids") @PathParam("operationIds") String operationIds, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - return delete(interfaceId, operationIds, serviceId, request, userId); + @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("/services/{serviceId}/interfaces/{interfaceId}/operations/{operationIds}") - @ApiOperation(value = "Get Interface Operations from Service", httpMethod = "GET", notes = "GET Interface Operations from Service", response = Response.class) - @ApiResponses(value = { - @ApiResponse(code = 201, message = "Get Interface Operations from Service"), - @ApiResponse(code = 400, message = "Invalid content / Missing content"), + @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 = 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 = "Comma seperated value of operationIds") @PathParam("operationIds") String operationIds, - @HeaderParam(value = Constants.USER_ID_HEADER) String userId, - @Context final HttpServletRequest request) { - return get(interfaceId, operationIds, serviceId, request, userId); + @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 interfaceId, String operationIds, String componentId, HttpServletRequest request, String userId){ + private Response get (String interfaceOperationId, String componentId, HttpServletRequest request, String userId){ ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); @@ -230,14 +145,15 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { 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); + 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()); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), getFormattedResponse(actionResponse.left().value())); + InterfaceOperationDataDefinition interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(actionResponse.left().value()); + Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Get Component interface operations"); @@ -246,7 +162,8 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { } } - private Response delete (String interfaceId, String operationIds, String componentId, HttpServletRequest request, String userId){ + private Response delete (String interfaceOperationId, String componentId, HttpServletRequest + request, String userId){ ServletContext context = request.getSession().getServletContext(); String url = request.getMethod() + " " + request.getRequestURI(); @@ -259,14 +176,15 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { String componentIdLower = componentId.toLowerCase(); InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context); - 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); + 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()); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), getFormattedResponse(actionResponse.left().value())); + InterfaceOperationDataDefinition interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(actionResponse.left().value()); + Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Delete Interface Operation"); @@ -275,7 +193,7 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { } } - private Response createOrUpdate (String data, ComponentTypeEnum componentType, String componentId, HttpServletRequest request, String userId, boolean isUpdate) { + 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(); @@ -287,12 +205,12 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { String componentIdLower = componentId.toLowerCase(); InterfaceOperationBusinessLogic businessLogic = getInterfaceOperationBL(context); - List<InterfaceDefinition> mappedInterfaceData = getMappedInterfaceData(data, modifier, componentType); - Either<List<InterfaceDefinition>, ResponseFormat> actionResponse ; + Operation operation = getMappedOperationData(data, isUpdate, modifier, ComponentTypeEnum.findByParamName(componentType)); + Either<Operation, ResponseFormat> actionResponse ; if (isUpdate) { - actionResponse = businessLogic.updateInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true); + actionResponse = businessLogic.updateInterfaceOperation(componentIdLower, operation, modifier, true); } else { - actionResponse = businessLogic.createInterfaceOperation(componentIdLower, mappedInterfaceData, modifier, true); + actionResponse = businessLogic.createInterfaceOperation(componentIdLower, operation, modifier, true); } if (actionResponse.isRight()) { @@ -300,7 +218,9 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { return buildErrorResponse(actionResponse.right().value()); } - return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), getFormattedResponse(actionResponse.left().value())); + InterfaceOperationDataDefinition interfaceOperationDataDefinition = InterfaceUIDataConverter.convertOperationDataToInterfaceData(actionResponse.left().value()); + Object result = RepresentationUtils.toFilteredRepresentation(interfaceOperationDataDefinition); + return buildOkResponse(getComponentsUtils().getResponseFormat(ActionStatus.OK), result); } catch (Exception e) { BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Interface Operation Creation or update"); @@ -309,16 +229,16 @@ public class InterfaceOperationServlet extends AbstractValidationsServlet { } } - 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 uiComponentEither.left().value().getInterfaces().values().stream().collect(Collectors.toList()); - } - - private Object getFormattedResponse(List<InterfaceDefinition> interfaceDefinitions) throws IOException { - Map<String, List<InterfaceDefinition>> allInterfaces = ImmutableMap.of(JsonPresentationFields.INTERFACES.getPresentation(), interfaceDefinitions); - return RepresentationUtils.toFilteredRepresentation(allInterfaces); + 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()); + } + 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 239c0421a1..dbdfaa9897 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 @@ -32,22 +32,20 @@ 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); @@ -190,8 +188,11 @@ 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) - .build(); + .put(InterfaceOperationDataDefinition.class,IsEmptyFilterMixIn.class).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 ff6d7d662f..69c4cec42b 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,7 +45,6 @@ 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; @@ -56,9 +55,7 @@ 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; @@ -73,7 +70,6 @@ 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; @@ -116,12 +112,11 @@ 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, InterfaceLifecycleOperation interfaceLifecycleOperation) { + GroupExportParser groupExportParser, InputConverter inputConverter) { this.dataTypeCache = dataTypeCache; this.toscaOperationFacade = toscaOperationFacade; this.capabilityRequirementConverter = capabilityRequirementConverter; @@ -129,7 +124,6 @@ public class ToscaExportHandler { this.groupExportParser = groupExportParser; this.propertyConvertor = PropertyConvertor.getInstance(); this.inputConverter = inputConverter; - this.interfaceLifecycleOperation = interfaceLifecycleOperation; } @@ -559,15 +553,7 @@ public class ToscaExportHandler { boolean isAssociatedResourceComponent) { log.debug("start convert node type for {}", component.getUniqueId()); ToscaNodeType toscaNodeType = createNodeType(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)); - + toscaNode.setInterface_types(addInterfaceTypeElement(component)); 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 ef3023de6b..7afad74f64 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, List<String> allInterfaceTypes) { + public static Map<String, Object> addInterfaceTypeElement(Component component) { if (component instanceof Product) { return null; } @@ -68,28 +68,24 @@ public class InterfacesOperationsToscaUtil { if (MapUtils.isEmpty(interfaces)) { return null; } - Map<String, Object> toscaInterfaceTypes = new HashMap<>(); for (InterfaceDefinition interfaceDefinition : interfaces.values()) { - boolean isInterfaceTypeExistInGlobalType = allInterfaceTypes.stream().anyMatch(type -> type.equalsIgnoreCase(interfaceDefinition.getType())); - if(!isInterfaceTypeExistInGlobalType){ - ToscaInterfaceNodeType toscaInterfaceType = new ToscaInterfaceNodeType(); - toscaInterfaceType.setDerived_from(DERIVED_FROM_STANDARD_INTERFACE); + 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(), + 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); - - toscaInterfaceTypes.put(interfaceDefinition.getType(), interfacesAsMap); } + 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); } return MapUtils.isNotEmpty(toscaInterfaceTypes) ? toscaInterfaceTypes : null; } @@ -112,8 +108,8 @@ public class InterfacesOperationsToscaUtil { Map<String, Object> toscaInterfaceDefinitions = new HashMap<>(); for (InterfaceDefinition interfaceDefinition : interfaces.values()) { ToscaInterfaceDefinition toscaInterfaceDefinition = new ToscaInterfaceDefinition(); - final String interfaceType = interfaceDefinition.getType(); - toscaInterfaceDefinition.setType(interfaceType); + final String toscaResourceName = interfaceDefinition.getToscaResourceName(); + toscaInterfaceDefinition.setType(toscaResourceName); final Map<String, OperationDataDefinition> operations = interfaceDefinition.getOperations(); Map<String, Object> toscaOperations = new HashMap<>(); @@ -137,7 +133,7 @@ public class InterfacesOperationsToscaUtil { Map<String, Object> operationsMap = (Map<String, Object>) interfaceDefAsMap.remove(OPERATIONS_KEY); handleDefaults(operationsMap); interfaceDefAsMap.putAll(operationsMap); - toscaInterfaceDefinitions.put(getLastPartOfName(interfaceType), interfaceDefAsMap); + toscaInterfaceDefinitions.put(getLastPartOfName(toscaResourceName), interfaceDefAsMap); } if (MapUtils.isNotEmpty(toscaInterfaceDefinitions)) { nodeType.setInterfaces(toscaInterfaceDefinitions); diff --git a/catalog-be/src/main/resources/config/error-configuration.yaml b/catalog-be/src/main/resources/config/error-configuration.yaml index a9d090995b..84213bbe8d 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: 409, + code: 400, message: "Error: Interface Operation name '%1' already in use, Your current changes will not be saved.", messageId: "SVC4695" } @@ -2046,15 +2046,15 @@ errors: } #---------SVC4697----------------------------- INTERFACE_OPERATION_NAME_MANDATORY: { - code: 400, + code: 404, message: "Error: Interface Operation name is mandatory, Operation name can't be empty.", messageId: "SVC4697" } #---------SVC4698----------------------------- -# %1 - Interface type - INTERFACE_OPERATION_INVALID_FOR_LOCAL_TYPE: { +# %1 - Interface Operation description + INTERFACE_OPERATION_DESCRIPTION_MAX_LENGTH: { code: 400, - message: "Error: Invalid input, only one operation is allowed in local interface type '%1'.", + message: "Error: Interface Operation description '%1' is invalid, maximum 200 characters allowed.", messageId: "SVC4698" } #---------SVC4699----------------------------- @@ -2066,20 +2066,20 @@ errors: } #---------SVC4700----------------------------- INTERFACE_OPERATION_INPUT_NAME_MANDATORY: { - code: 400, + code: 404, message: "Error: Interface operation input parameter name should not be empty.", messageId: "SVC4700" } #---------SVC4701----------------------------- -# %1 - component Id +# %1 - resource Id INTERFACE_OPERATION_NOT_FOUND: { code: 404, - message: "Error: Interface operation not found in the component '%1'.", + message: "Error: Interface operation not found in the resource '%1'.", messageId: "SVC4701" } #---------SVC4702----------------------------- INTERFACE_OPERATION_NOT_DELETED: { - code: 400, + code: 404, message: "Error: Failed to delete interface operation.", messageId: "SVC4702" } @@ -2133,43 +2133,29 @@ errors: message: "Error: CSAR packaging failed for %1 %2.", messageId: "SVC4706" } -#---------SVC4708----------------------------- -# %1 - Interface Operation input property name, component type +#---------SVC4704----------------------------- +# %1 - Interface Operation input property name INTERFACE_OPERATION_INPUT_PROPERTY_NOT_FOUND_IN_COMPONENT: { code: 404, - message: "Error: Interface operation input parameter property '%1' not found in '%2' input properties.", - messageId: "SVC4708" + message: "Error: Interface operation input parameter property '%1' not found in component input properties.", + messageId: "SVC4704" } -#---------SVC4709----------------------------- +#---------SVC4705----------------------------- # %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: "SVC4708" + messageId: "SVC4705" } -#---------SVC4710----------------------------- +#---------SVC4706----------------------------- INTERFACE_OPERATION_OUTPUT_NAME_MANDATORY: { - code: 400, + code: 404, message: "Error: Interface operation output parameter name should not be empty.", - messageId: "SVC4710" - } -#---------SVC4711----------------------------- -# %1 - interface Id - INTERFACE_NOT_FOUND_IN_COMPONENT: { - code: 404, - message: "Error: Interface not found in the component '%1'.", - messageId: "SVC4711" + messageId: "SVC4706" } #---------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/InterfaceOperationBusinessLogicTest.java b/catalog-be/src/test/java/org/openecomp/sdc/be/components/impl/InterfaceOperationBusinessLogicTest.java index 997d32691b..f2d8b57dbf 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,321 +18,432 @@ package org.openecomp.sdc.be.components.impl; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyCollection; 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.Arrays; -import java.util.Collections; +import java.util.ArrayList; 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.junit.MockitoJUnitRunner; -import org.openecomp.sdc.be.components.utils.ResourceBuilder; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.ElementOperationMock; +import org.openecomp.sdc.be.auditing.impl.AuditingManager; 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.model.InputDefinition; +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.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.IGraphLockOperation; +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.StorageOperationStatus; +import org.openecomp.sdc.be.model.operations.impl.GraphLockOperation; import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation; -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 { - @InjectMocks - 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 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_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 RESOURCE_NAME = "Resource1"; - private static final String operationId1 = "operationId1"; - private static final String interfaceId1 = "interfaceId1"; - private User user; - private Resource resource; + 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(); + + @InjectMocks + private + InterfaceOperationBusinessLogic bl = new InterfaceOperationBusinessLogic(); @Before public void setup() { - resource = new ResourceBuilder() - .setComponentType(ComponentTypeEnum.RESOURCE) - .setUniqueId(resourceId) - .setName(RESOURCE_NAME) - .build(); - resource.setInterfaces(InterfaceOperationTestUtils.createMockInterfaceDefinitionMap(interfaceId, operationId)); - resource.setInputs(createInputsForResource()); + MockitoAnnotations.initMocks(this); + Mockito.reset(propertyOperation); - 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); - } + ExternalConfiguration.setAppName("catalog-be"); - @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()); - } + // 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)); - @Test - 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()); - } + // Elements + IElementOperation mockElementDao = new ElementOperationMock(); - @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()); + // 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 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()); - } + 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())); - @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); + 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 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()); - } + 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())); - @Test - 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); + Either<Operation, ResponseFormat> interfaceOperation = bl.createInterfaceOperation(resourceId, operation, user, true); Assert.assertTrue(interfaceOperation.isLeft()); + } @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, operationId1)), user, true); + 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)); + + Either<Operation, ResponseFormat> interfaceOperation = bl.createInterfaceOperation(resourceId, operation, user, true); Assert.assertTrue(interfaceOperation.isRight()); - } - @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()); } - @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 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 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()); + when(interfaceOperation.addInterfaceOperation(any(), any(), any())).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); + Assert.assertTrue(bl.createInterfaceOperation(resourceId, operation, user, true).isRight()); } @Test - public void deleteInterfaceOperationTestInterfaceDoesntExist() { - Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId1, Collections.singletonList(operationId), user, true).isRight()); + 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())); + + Either<Operation, ResponseFormat> interfaceOperation = bl.updateInterfaceOperation(resourceId, operation, user, true); + Assert.assertTrue(interfaceOperation.isLeft()); } - @Test - public void deleteInterfaceOperationTestOperationDoesntExist() { - Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, Collections.singletonList(operationId1), 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 deleteInterfaceOperationTestSuccess() { - resource.getInterfaces().get(interfaceId).getOperations().putAll(InterfaceOperationTestUtils.createMockOperationMap(operationId1)); + 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())); when(artifactCassandraDao.deleteArtifact(any(String.class))).thenReturn(CassandraOperationStatus.OK); - when(interfaceOperation.updateInterfaces(any(), any())).thenReturn(Either.left(Collections.emptyList())); - Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, Collections.singletonList(operationId), user, true).isLeft()); + Either<Operation, ResponseFormat> deleteResourceResponseFormatEither = bl.deleteInterfaceOperation(resourceId, operationId, user, true); + Assert.assertTrue(deleteResourceResponseFormatEither.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); - when(interfaceOperation.updateInterfaces(any(), any())).thenReturn(Either.right(StorageOperationStatus.GENERAL_ERROR)); - Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, Collections.singletonList(operationId), user, true).isRight()); - } + Assert.assertTrue(bl.deleteInterfaceOperation(resourceId, 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 deleteInterfaceOperationTestFailOnException() { - when(artifactCassandraDao.deleteArtifact(any(String.class))).thenThrow(new RuntimeException()); - Assert.assertTrue(interfaceOperationBusinessLogic.deleteInterfaceOperation(resourceId, interfaceId, Collections.singletonList(operationId), user, true).isRight()); + 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()); } @Test - 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()); + 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()); } @Test - 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()); + 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()); } - @Test - public void getInterfaceOperationTestInterfaceDoesntExist() { - Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId1, 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 getInterfaceOperationTestOperationDoesntExist() { - Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId, Collections.singletonList(operationId1), user, true).isRight()); + private void validateUserRoles(Role... roles) { + List<Role> listOfRoles = Stream.of(roles).collect(Collectors.toList()); } - @Test - public void getInterfaceOperationTest() { - Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId, Collections.singletonList(operationId), user, true).isLeft()); + private void setCanWorkOnResource(Resource resource) { + resource.setLifecycleState(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + resource.setLastUpdaterUserId(user.getUserId()); } - @Test - public void getInterfaceOperationTestFailOnException() { - when(titanDao.commit()).thenThrow(new RuntimeException()); - Assert.assertTrue(interfaceOperationBusinessLogic.getInterfaceOperation(resourceId, interfaceId, Collections.singletonList(operationId), user, true).isRight()); + 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 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 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 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()); + 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 testGetAllInterfaceLifecycleTypes_TypesNotFound() { when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()).thenReturn(Either.right(StorageOperationStatus.NOT_FOUND)); - Either<Map<String, InterfaceDefinition>, ResponseFormat> response = interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(); + Either<Map<String, InterfaceDefinition>, ResponseFormat> response = bl.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(interfaceId); - interfaceDefinition.setType(interfaceId); + interfaceDefinition.setUniqueId(UNIQUE_ID); + interfaceDefinition.setType(TYPE); Map<String, InterfaceDefinition> interfaceDefinitionMap = new HashMap<>(); interfaceDefinitionMap.put(interfaceDefinition.getUniqueId(), interfaceDefinition); when(interfaceLifecycleOperation.getAllInterfaceLifecycleTypes()).thenReturn(Either.left(interfaceDefinitionMap)); - Either<Map<String, InterfaceDefinition>, ResponseFormat> response = interfaceOperationBusinessLogic.getAllInterfaceLifecycleTypes(); + Either<Map<String, InterfaceDefinition>, ResponseFormat> response = bl.getAllInterfaceLifecycleTypes(); Assert.assertEquals(response.left().value().size(),1); } - - 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); - } }
\ 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 8e35981722..b6a7c98efa 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,6 +32,7 @@ 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; @@ -59,6 +60,7 @@ 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; @@ -154,6 +156,8 @@ 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(); @@ -224,6 +228,7 @@ 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); @@ -240,6 +245,7 @@ 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); @@ -261,6 +267,8 @@ 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); @@ -942,6 +950,7 @@ 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 @@ -963,6 +972,7 @@ 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 @@ -986,6 +996,7 @@ 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 deleted file mode 100644 index 8884f9f2d6..0000000000 --- a/catalog-be/src/test/java/org/openecomp/sdc/be/components/utils/InterfaceOperationUtilsTest.java +++ /dev/null @@ -1,80 +0,0 @@ -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 43d2fe884f..1a112c583b 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,246 +19,264 @@ package org.openecomp.sdc.be.components.validation; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -import java.util.Arrays; -import java.util.Collections; +import com.google.common.collect.Sets; +import fj.data.Either; + +import java.util.ArrayList; +import java.util.Collection; 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.Component; +import org.openecomp.sdc.be.model.ComponentInstanceInput; 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 ResponseFormatManager responseFormatManagerMock; + private final InterfaceOperationValidationUtilTest interfaceOperationValidationUtilTest = new InterfaceOperationValidationUtilTest(); private final ListDataDefinition<OperationInputDefinition> operationInputDefinitionList = new ListDataDefinition<>(); private final ListDataDefinition<OperationOutputDefinition> operationOutputDefinitionList = new ListDataDefinition<>(); - 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 Component component; - private ResponseFormatManager responseFormatManagerMock; @Before - public void setup() { + public void init() { 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(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()); + 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()); } @Test - public void shouldFailWhenOperationNameIsEmpty() { - 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()); + 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()); } + + @Test - 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()); + 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()); } @Test - 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()); + 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()); } @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 " + + 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"); - Assert.assertTrue(interfaceOperationValidationUtilTest.validateInterfaceOperations(interfaceDefinition, component, component.getInterfaces().get(interfaceId), Collections.emptyMap(),false).isRight()); + Either<Boolean, ResponseFormat> booleanResponseFormatEither = interfaceOperationValidationUtilTest + .validateInterfaceOperations(operations, component, false); + Assert.assertTrue(booleanResponseFormatEither.isRight()); } + @Test public void shouldFailWhenOperationInputParamNamesAreNotUnique() { - 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()); + 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()); } @Test public void shouldPassWhenOperationInputParamNamesAreUnique() { - 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()); + 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()); } @Test public void shouldPassWhenOperationInputParamNamesHasSubProperty() { - 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()); + 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()); } @Test public void shouldFailWhenOperationInputParamNameEmpty() { operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(" ")); - 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()); + 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()); } @Test public void shouldFailWhenOperationOutputParamNameEmpty() { - operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition(inputId)); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("inputParam")); + operationInputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationInputDefinition("label1")); operationOutputDefinitionList.add(InterfaceOperationTestUtils.createMockOperationOutputDefinition(" ")); - InterfaceDefinition interfaceDefinition = createInterfaceOperationData(operationId2, operationId2,new ArtifactDefinition(), operationInputDefinitionList, operationOutputDefinitionList,"update"); - Assert.assertTrue(interfaceOperationValidationUtilTest.validateInterfaceOperations(interfaceDefinition, component, component.getInterfaces().get(interfaceId), Collections.emptyMap(),false).isRight()); + 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()); } @Test public void shouldPassWhenInterfaceOperationOutputParamNamesUnique() { - 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()); + 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()); } @Test public void shouldFailWhenOperationOutputParamNamesAreNotUnique() { - 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()); + 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()); } - @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 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 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()); - } - - @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()); - } - - @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 Component setUpComponentMock(){ + Component component = new Resource(); - @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()); - } + List<InputDefinition> inputs = new ArrayList<>(); + InputDefinition inputDefinition = new InputDefinition(); + InputDefinition inputDefinition1 = new InputDefinition(); - @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()); + 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); + + inputDefinition.setUniqueId("inputId1"); + inputDefinition.setInputs(componentInstanceInputs); + inputDefinition1.setUniqueId("uniqueId3"); + + inputs.add(inputDefinition); + inputs.add(inputDefinition1); + component.setInputs(inputs); + component.setInterfaces(createMockInterfaceDefinition()); + return component; } - 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; - } + 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)); - 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); + return interfaceDefinitionMap; } 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 new file mode 100644 index 0000000000..0c02e71bd2 --- /dev/null +++ b/catalog-be/src/test/java/org/openecomp/sdc/be/datamodel/utils/InterfaceUIDataConverterTest.java @@ -0,0 +1,104 @@ +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 592d27ec5d..2fabe43733 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,7 +1,6 @@ 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; @@ -47,7 +46,6 @@ 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; @@ -84,9 +82,6 @@ public class ToscaExportHandlerTest extends BeConfDependentTest { @Mock GroupExportParserImpl groupExportParserImpl; - @Mock - InterfaceLifecycleOperation interfaceLifecycleOperation; - @Before public void setUpMock() throws Exception { MockitoAnnotations.initMocks(this); @@ -165,7 +160,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); @@ -397,7 +392,6 @@ 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 983ef91a8c..8f34e0e29b 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,7 +19,6 @@ 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; @@ -64,15 +63,15 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Resource(); component.setNormalizedName("normalizedComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setType("interface.types.test_resource_name"); + addedInterface.setToscaResourceName("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, new ArrayList<>()); + InterfacesOperationsToscaUtil.addInterfaceTypeElement(component); - ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); + ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null); ToscaTemplate template = new ToscaTemplate("test"); template.setInterface_types(interfaceTypeElement); final ToscaRepresentation toscaRepresentation = handler.createToscaRepresentation(template); @@ -86,15 +85,15 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Service(); component.setNormalizedName("normalizedServiceComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setType("interface.types.test_service_name"); + addedInterface.setToscaResourceName("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, new ArrayList<>()); + InterfacesOperationsToscaUtil.addInterfaceTypeElement(component); - ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); + ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null); ToscaTemplate template = new ToscaTemplate("testService"); template.setInterface_types(interfaceTypeElement); final ToscaRepresentation toscaRepresentation = handler.createToscaRepresentation(template); @@ -108,7 +107,7 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Resource(); component.setNormalizedName("normalizedComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setType("com.some.resource.or.other.resourceName"); + addedInterface.setToscaResourceName("com.some.resource.or.other.resourceName"); addOperationsToInterface(addedInterface, 3, 2, true); final String interfaceType = "normalizedComponentName-interface"; @@ -117,7 +116,7 @@ public class InterfacesOperationsToscaUtilTest { ToscaNodeType nodeType = new ToscaNodeType(); InterfacesOperationsToscaUtil.addInterfaceDefinitionElement(component, nodeType, false); - ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); + ToscaExportHandler handler = new ToscaExportHandler(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); @@ -140,7 +139,8 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Service(); component.setNormalizedName("normalizedServiceComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setType("com.some.service.or.other.serviceName"); + addedInterface.setToscaResourceName("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, null); + ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null); ToscaTemplate template = new ToscaTemplate("testService"); Map<String, ToscaNodeType> nodeTypes = new HashMap<>(); nodeTypes.put(NODE_TYPE_NAME, nodeType); @@ -170,7 +170,8 @@ public class InterfacesOperationsToscaUtilTest { Component component = new Resource(); component.setNormalizedName("normalizedComponentName"); InterfaceDefinition addedInterface = new InterfaceDefinition(); - addedInterface.setType("com.some.resource.or.other.resourceNameNoInputs"); + addedInterface.setToscaResourceName("com.some.resource.or.other.resourceNameNoInputs"); + addOperationsToInterface(addedInterface, 3, 3, false); final String interfaceType = "normalizedComponentName-interface"; component.setInterfaces(new HashMap<>()); @@ -178,7 +179,7 @@ public class InterfacesOperationsToscaUtilTest { ToscaNodeType nodeType = new ToscaNodeType(); InterfacesOperationsToscaUtil.addInterfaceDefinitionElement(component, nodeType, false); - ToscaExportHandler handler = new ToscaExportHandler(null,null,null,null,null,null, null); + ToscaExportHandler handler = new ToscaExportHandler(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 4bda41671d..10acd69a79 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,7 +27,7 @@ import org.openecomp.sdc.be.model.Operation; public class InterfaceOperationTestUtils { - private static InterfaceDefinition createInterface(String uniqueID, String description, String type, + public static InterfaceDefinition createInterface(String uniqueID, String description, String type, String toscaResourceName, Map<String, Operation> op) { InterfaceDefinition id = new InterfaceDefinition(); id.setType(type); @@ -38,35 +38,48 @@ public class InterfaceOperationTestUtils { return id; } - 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 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 InterfaceDefinition createMockInterface(String interfaceId, String operationId) { - return createInterface(interfaceId, interfaceId, interfaceId, interfaceId, createMockOperationMap(operationId)); + public static Operation mockOperationToReturn() { + return createMockOperation(); } - public static Map<String, Operation> createMockOperationMap(String operationId) { + public static Map<String, Operation> createMockOperationMap() { Map<String, Operation> operationMap = new HashMap<>(); - operationMap.put(operationId, createMockOperation(operationId)); + operationMap.put("op1", createMockOperation()); return operationMap; } - public static Operation createMockOperation(String operationId) { + public static Operation createMockOperation() { Operation operation = new Operation(); ListDataDefinition<OperationInputDefinition> operationInputDefinitionList = new ListDataDefinition<>(); - operationInputDefinitionList.add(createMockOperationInputDefinition("inputId")); + operationInputDefinitionList.add(createMockOperationInputDefinition("label1")); operation.setInputs(operationInputDefinitionList); ListDataDefinition<OperationOutputDefinition> operationOutputDefList = new ListDataDefinition<>(); - operationOutputDefList.add(createMockOperationOutputDefinition("outputId")); + operationOutputDefList.add(createMockOperationOutputDefinition("op1")); operation.setOutputs(operationOutputDefList); operation.setDefinition(false); - operation.setName(operationId); - operation.setUniqueId(operationId); + operation.setName("CREATE"); + operation.setUniqueId("uniqueId1"); ArtifactDefinition implementation = new ArtifactDefinition(); implementation.setUniqueId("uniqId"); implementation.setArtifactUUID("artifactId"); @@ -76,39 +89,28 @@ public class InterfaceOperationTestUtils { return operation; } - public static OperationInputDefinition createMockOperationInputDefinition(String inputId) { + public static OperationInputDefinition createMockOperationInputDefinition(String name) { OperationInputDefinition operationInputDefinition = new OperationInputDefinition(); - operationInputDefinition.setName(inputId); - operationInputDefinition.setUniqueId(inputId); - operationInputDefinition.setInputId(inputId); - operationInputDefinition.setValue(inputId); - operationInputDefinition.setDefaultValue(inputId); + operationInputDefinition.setName(name); + operationInputDefinition.setUniqueId("uniqueId1"); + operationInputDefinition.setInputId("inputId1"); return operationInputDefinition; } - public static OperationOutputDefinition createMockOperationOutputDefinition(String outputId) { + public static OperationOutputDefinition createMockOperationOutputDefinition(String name) { OperationOutputDefinition operationOutputDefinition = new OperationOutputDefinition(); - operationOutputDefinition.setName(outputId); - operationOutputDefinition.setUniqueId(outputId); - operationOutputDefinition.setInputId(outputId); - operationOutputDefinition.setValue(outputId); - operationOutputDefinition.setDefaultValue(outputId); + operationOutputDefinition.setName(name); + operationOutputDefinition.setUniqueId("uniqueId1"); + operationOutputDefinition.setInputId("inputId1"); return operationOutputDefinition; } - public static Map<String, InterfaceDefinition> createMockInterfaceTypeMap(String interfaceType, String operationType) { - Map<String, Operation> operationMap = createMockOperationTypeMap(operationType); + public static Map<String, InterfaceDefinition> createMockInterfaceDefinition(String resourceName) { + Map<String, Operation> operationMap = createMockOperationMap(); Map<String, InterfaceDefinition> interfaceDefinitionMap = new HashMap<>(); - interfaceDefinitionMap.put(interfaceType, createInterface(interfaceType, interfaceType, interfaceType, interfaceType, operationMap)); + interfaceDefinitionMap.put("int1", createInterface("int1", "Interface 1", + "lifecycle", "org.openecomp.interfaces.node.lifecycle." + resourceName, 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; - } - } |